2016-01-15 48 views
0

我正在使用導航抽屜,Fragment_1包含一個listview,它搜索gps位置,然後加載適配器。如果我保持Fragment_1處於打開狀態,直到它完全加載,則該過程可以正常工作。但是,如果我在Fragment_1搜索位置或加載適配器時嘗試打開另一個片段Fragment_2,則我的應用程序崩潰。 Fragment_2支持textview,如果單獨啓動,則可以正常工作。從現有片段啓動其他片段時應用程序崩潰

我使用下面的代碼從抽屜

推出新片段
Fragment mFragment; 
FragmentManager mFragmentManager = getSupportFragmentManager(); 
mFragment = new Fragment_2();         

mFragmentManager.beginTransaction() 
.replace(R.id.frame_container,mFragment) 
.commit(); 
+1

請粘貼你的logcat輸出 –

+0

如果應用程序崩潰,那麼你不應該發佈你的logcat錯誤。沒有這個,我們只能推測原因。 – Rohit5k2

回答

1

您應該加載列表做一個異步任務。在替換當前片段之前,只需取消異步任務。如果任務沒有被取消,請確保您檢查onPostExecute。

在這裏您可以找到將異步數據加載到回收站視圖的示例:http://javatechig.com/android/android-recyclerview-example。看看AsyncHttpTask。您可以看到數據在doInBackground上進行採集和分析,並顯示在onPostExecute中。您還需要將以下內容添加到您的代碼:關於分離的

if (!isCancelled()) { 
    /* your code here for setting list adapter */ 
} 

覆蓋在onPostExecute附上一切:

@Override 
public void onDetach() { 
    super.onDetach(); 

    // don't update the UI if user go from this fragment 
    if (displayResultsAsyncTask != null && !displayResultsAsyncTask.isCancelled()) 
     displayResultsAsyncTask.cancel(true); 
} 

所以,你的代碼看起來應該是這樣的:

public class YourFragment extends Fragment { 
    // declare an async task in your fragment 
    private AsyncTask displayResultsAsyncTask = null; 
    /* other data here */ 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     /* your code for onCreate */ 
     GetAndDisplayResults(); // call display results 
    } 

    public void GetAndDisplayResults() { 
     displayResultsAsyncTask = new AsyncTask<String, Void, Integer>() { 
      @Override 
      protected Integer doInBackground(String... params) { 
       Integer result = 0; 

       // get and parse data, also set result 

       return result; 
      } 

      @Override 
      protected void onPostExecute(Integer result) { 
       if (!isCancelled()) { 
        // if task wasn't stopped 
        if (result == 1) 
         SetYourList(); // set your list adapter based on results returned from doInBackground 
       } 
      } 
     }.execute(); 
    } 

    @Override 
    public void onDetach() { 
     super.onDetach(); 

     // don't update the UI if user go from this fragment 
     if (displayResultsAsyncTask != null && !displayResultsAsyncTask.isCancelled()) 
      displayResultsAsyncTask.cancel(true); 
    } 
} 

用於保存數據的列表可以全局聲明,並可以從doInBackground和onPostExecute中聲明,也可以作爲參數派生爲onPostExecute。

+0

如果片段需要刪除,沒有意義。 – Rohit5k2

+0

我正在使用listview加載的改造,你能告訴我如何實現這個?應用程序在找到位置並嘗試加載適配器後崩潰。 –

0

它看起來像你正試圖commitfragmentTransaction中的onCreateonResume方法這是造成由於activity state loss例外IllegalStateException: Can not perform this action after onSaveInstanceState之一。請檢查您是否正在執行這些功能。

希望這會有所幫助。

+0

是的,我在我的onCreate中調用它,可能的解決方案是什麼? –

+0

'onPostResume()'將成爲您的解決方案 –

+0

我正在使用改進加載我的列表視圖,你能告訴我在這種情況下可以做些什麼。 –

相關問題