2014-10-20 112 views
0

我有一个活动, 它的一些片段我要去数据库获取数据。问题在回来的路上。android在活动中保存活动

当后退按钮按下时,片段将再次获取数据。 我需要它只获取一次数据(数据不会丢失)。 什么是正确的做法?

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

     View v = inflater.inflate(R.layout.from_opening_to_plan, container, 
       false); 



     setRetainInstance(true); //work only once. 


     // --- Sending Data to Server -----// 
     startLoading(); 
     ParseCloud.callFunctionInBackground(funcName, h, 
       new FunctionCallback<Object>() { 
      @SuppressWarnings("unchecked") 
      public void done(Object result, ParseException e) { 
       if (e == null) { 
        results = ((HashMap<String, Object>) result); 
        stopLoading(); 
       } 
       else{ 
        stopLoading(); 
       } 
      } 
     }); 


     return v; 
    } 

    protected void startLoading() { 
     proDialog = new ProgressDialog(this.getActivity(),ProgressDialog.THEME_HOLO_DARK); 
     proDialog.setMessage("Loading ..."); 
     proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     proDialog.setCancelable(false); 
     proDialog.show(); 
    } 

    protected void stopLoading() { 
     proDialog.dismiss(); 
     proDialog = null; 

     // Build the page from the results. 
     makePage(); 
    } 

    @SuppressWarnings("deprecation") 
    public void makePage() { 
     LinearLayout ll_buttons = (LinearLayout) v2 
       .findViewById(R.id.buttons_frame); 
     LinearLayout ll_question = (LinearLayout) v2 
       .findViewById(R.id.question_frame); 

     TextView tv = new TextView(container2.getContext()); 
     String text = (((HashMap) results).get("textPrefix").toString()); 
     text = text.replace("\r", "\r\n\r\n "); 
      .... 
      .... 

      b1.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View v) { 
        .... 
       } 
      }); 
      ll_buttons.addView(b1); 
     } 

      v2.setBackgroundDrawable(SMApplication.selectedVertical.gd);   
    } 

回答

0

如果从片段的构造函数中调用setRetainInstance(true)片段将不会重新创建每次Activity被重建的时间,所以你只能获取一次数据,如果尚未取出。

+0

它仍然工作的同 – igor 2014-10-21 07:56:06

+0

你还没有发布任何代码,所以它不可能看到会发生什么 – 2014-10-21 07:57:34

+0

添加一个代码,也许我应该用onBack()使用一些东西? – igor 2014-10-21 08:12:45

0

找到解决方案(如果有人有一个更好的,请张贴):

添加的onResume功能:

private boolean resumeHasRun = false; 

@Override 
public void onResume() { 
    super.onResume(); 
    if (!resumeHasRun) { 
     resumeHasRun = true; 
     return; 
    } 
    makePage(); 
    // Normal case behavior follows 
} 
在OnCreate

补充:

if (resumeHasRun) { 
    resumeHasRun = true; 
    return; 
}