2016-08-09 126 views
-1

我有一个表单,我在填写详细信息&以获取我正在使用的位置Google Maps。但是当我从地图获取位置后回到活动时,所有字段都是null重新创建实例

如何在移动到地图之前存储状态,并在从地图活动回来后获取确切的状态?

编辑:片段的onCreate

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    super.onCreateView(inflater, container, savedInstanceState); 

    // Here I used recreate but it didn't work 
    // getActivity.recreate(); 

    View view = inflater.inflate(R.layout.fragment_login, container, false); 
    ButterKnife.bind(this, view); 
    return view; 
} 

从这里我要去映射活动

@OnClick(R.id.frag_expense_lllocation) 
    public void getLocation(){ 
     UiActivity.startMapActivity(context); 
    } 

,并回到当前活动与选定的位置

double lat = marker.getPosition().latitude;                
double lng =  marker.getPosition().longitude;                
String position = lat + "," + lng;   
UiActivity.startExpenseActivity(getContext(), position); 
getActivity().finish(); 
+1

后您的代码.... – RajSharma

+0

@RajSharma我已经上传我的代码 – rookieDeveloper

回答

0

@gaurav你可以使用onSaveInstanceState()和onRestoreInstanceState()调用 回来很容易完成这项任务。

在第一个回调中,您需要保存您想要保存的状态 ,然后从第二个状态恢复状态。 有关进一步的信息,你可以检查的答案How to use onSaveInstanceState() and onRestoreInstanceState()

+0

我必须使用这两者在onCreate之前? – rookieDeveloper

+0

不,你只需要定义回调正文即可 – Alok

+1

此外,这些方法是回调,所以你不需要打电话,一切都由平台照顾。 – Alok

0

当您的活动开始停止,系统调用onSaveInstanceState(),因此您的活动可以保存状态信息与键值对的集合。此方法的默认实现保存有关活动视图层次结构状态的信息,例如EditText小部件中的文本或ListView的滚动位置。

要保存活动的附加状态信息,必须实现onSaveInstanceState()并将键/值对添加到Bundle对象。例如:

你需要重写

onSaveInstanceState(Bundle savedInstanceState) 

写你想改变的捆绑参数这样的应用程序的状态值:

static final String STATE_SCORE = "playerScore"; 
static final String STATE_LEVEL = "playerLevel"; 
... 

@Override 
public void onSaveInstanceState(Bundle savedInstanceState) { 
    // Save the user's current game state 
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore); 
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel); 

    // Always call the superclass so it can save the view hierarchy state 
    super.onSaveInstanceState(savedInstanceState); 
} 

恢复你的活动状态

当您的活动在之前被破坏后重新创建,您可以从系统通过活动的Bundle中恢复已保存的状态。 onCreate()和onRestoreInstanceState()回调方法都会收到包含实例状态信息的相同Bundle。

因为无论系统是在创建活动的新实例还是重新创建前一个实例,都会调用onCreate()方法,您必须在尝试读取之前检查状态Bundle是否为null。如果它为空,那么系统正在创建一个活动的新实例,而不是恢复之前被销毁的实例。

例如,下面是如何在的onCreate()恢复了一些状态数据:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); // Always call the superclass first 

    // Check whether we're recreating a previously destroyed instance 
    if (savedInstanceState != null) { 
     // Restore value of members from saved state 
     mCurrentScore = savedInstanceState.getInt(STATE_SCORE); 
     mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL); 
    } else { 
     // Probably initialize members with default values for a new instance 
    } 
    ... 
}