2013-06-21 105 views
0

我試圖將數據從活動A到FragmentActivity B的意圖傳遞給片段B.活動A的按鈕啓動FragmentActivity B.「年份」字符串設置一個過濾器與我查詢遠程服務器上的mysql數據庫。下面的代碼工作,但只有一半的時間。片段內的意圖只有一半的時間工作

我不知道是什麼導致它過濾一些時間,有時它只是返回未經過濾的整個表。我猜它必須與我在片段中使用的意圖有關,因爲過濾器在沒有片段的應用程序版本中沒有問題地工作。我將意圖從活動A發送到FragmentActivity B到碎片B的方式似乎效率不高。我該如何解決這個問題?

活動答:

Button button1 = (Button)findViewById(R.id.button1); 

    button1.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      Intent intent = new Intent(); 
      intent.setClass(FindMovie.this, ShowMovies.class); 

      intent.putExtra("year", year1); 

      startActivity(intent); 
    } 
    }); 

FragmentActivity B:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_show_movies); 
    if (getSupportFragmentManager().findFragmentByTag(TAG) == null) { 
     final FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
     ft.add(android.R.id.content, new ImageGridFragment(), TAG); 
     ft.commit(); 
    } 



    Intent i = getIntent(); 

    year = i.getStringExtra("year"); 

       //resend through another intent to the fragment B 
    Intent intent = new Intent(getApplicationContext(), ImageGridFragment.class); 


     intent.putExtra("year", year); 
    } 

片段B:

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


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


    Bundle extras = getActivity().getIntent().getExtras(); 

    year = extras.getString("year"); 

return v; 
    } 

回答

3

我覺得這是一個線程時機的問題,您FragmentActivityB創造的片段,這是發送到一個線程(我會想),然後你是從原來的新增值線程,有時第二個線程的速度足以在獲取新值之前執行FragmentB onCreateView。你可以做的是在FragmentTransaction期間添加'year'的值。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // Create a new fragment and bundle 
    Fragment fragment = new ImageGridFragment(); 
    Bundle bundle = new Bundle(); 

    // Put variables in bundle and add to fragment 
    bundle.putString("year", getIntent().getStringExtra("year")); 
    fragment.setArguments(bundle); 

    // Insert the fragment 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    fragmentManager 
      .beginTransaction() 
      .add(android.R.id.content, fragment) 
      .commit(); 
} 

在FragmentB得到'year'這樣的:

year = getArguments().getString("year");

我認爲這將解決這個問題,讓我知道什麼,雖然發生了,

乾杯。

+0

多麼美妙的答案!非常感謝。它解決了這個問題。 「線程計時問題」是問題所在,我實際上只需將異步任務移動到Bundle extras = getActivity()。getIntent()。getExtras(); \t \t \t \t year = extras.getString(「year」); – Jerome

+0

不客氣:D – LuckyMe

+0

LuckyMe,這真的有效。我有一個小問題,我的片段處於可選標籤視圖,所需片段位於第5個選項卡中。當我使用這個代碼時,它直接嵌入第5個屏幕。我如何改變它 –

相關問題