2012-10-13 4 views
4

FragmentActivity에서 Fragment로 매개 변수를 전달하려고하면 Fragment의 getArguments()에서 null 포인터 예외가 발생합니다. 여기 FragmentActivity에서 Fragment로 매개 변수 전달

여기 여기 내 FragmentActivity 코드

public class IndexChartActivity extends FragmentActivity { 
     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 

      setContentView(R.layout.index_chart); 

      IndexFragmentActivity indexFragment = 
(IndexFragmentActivity)getSupportFragmentManager().findFragmentById(R.id.index_fragment); 
      indexFragment.newInstance("ASPI"); 

     } 

    } 

인 index_chart.xml에게

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="#FFFFFF" 
    android:orientation="vertical" > 

    <fragment 
     android:id="@+id/header_fragment" 
     android:name="com.lk.ignitionit.cse.util.HeaderFragmentActivity" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

    <fragment 
     android:id="@+id/index_fragment" 
     android:name="com.lk.ignitionit.cse.util.IndexFragmentActivity" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

    <fragment 
     android:name="com.lk.ignitionit.cse.util.ChartFragmentActivity" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

</LinearLayout> 

이며, 여기에 조각

public class IndexFragmentActivity extends Fragment { 
    protected ImageView ivASPI; 
    protected ImageView ivMPI; 
    protected ImageView ivSP; 
    protected TextView tvMain; 
    protected TextView tvTop; 
    protected TextView tvBottom; 
    String response = null; 
    String result = null; 
    String [] resultArr = null; 
    Bundle b = new Bundle(); 
    String indexType = null; 
    int layout; 
    IndexFragmentActivity f = null; 

    public IndexFragmentActivity newInstance(String index) { 
     f = new IndexFragmentActivity(); 
     Bundle args = new Bundle(); 
     args.putString("indextype", index); 
     f.setArguments(args); 
     return f; 
    } 

    public String getSelectedIndex() { 
     return f.getArguments().getString("indextype"); 
    } 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     if(getSelectedIndex().equals("ASPI")){ 
      layout = R.layout.aspi_header; 
     }else if(getSelectedIndex().equals("MPI")){ 
      layout = R.layout.mpi_header; 
     }else{ 
      layout = R.layout.sp_header; 
     } 
     View view = inflater.inflate(layout, container, false); 

     tvMain = (TextView) view.findViewById(R.id.tv_main); 
     tvTop = (TextView) view.findViewById(R.id.tv_top); 
     tvBottom = (TextView) view.findViewById(R.id.tv_bottom); 


     new ServiceAccess().execute(""); 

     tvMain.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       b.putString("type", "S&P SL20"); 
       Activity activity = getActivity(); 
       Intent intent = new Intent(activity, IndexChartActivity.class); 
       intent.putExtras(b); 
       startActivity(intent); 

      } 
     }); 

     return view; 
    } 
} 

이고 나의 오류입니다

,622,

나는 이것과 관련된 많은 stackoverflow 질문을 언급하고 주어진 예제 코드를 시도했다 http://developer.android.com/guide/components/fragments.html. 이것이 내가 알아낼 수있는 매우 기본적인 문제가 될 것으로 보인다하지만 여전히 운이

정말 ..이 다시

답변

18
  1. 부터 Activity 없애 사전에

    덕분에 모든 피드를 감사하지 Activity으로부터 상속받지 않는 모든 클래스의 이름 예를 들어, IndexFragmentActivityActivity이 아닙니다.

  2. 실제 활동의 onCreate()에서 조각을 검색하려면 findFragmentById()을 호출 한 다음 해당 조각에서 newInstance()을 호출해야합니다. 그러나 단편은 처음으로 onCreate()이 호출 될 때 존재하지 않으며 여기서는 NullPointerException으로 실패합니다. 이 사건을 올바르게 처리하십시오. 자바

  3. 메소드 이름 newInstance 가장 일반적으로 newInstance() 일부 클래스의 인스턴스를 생성하기 위해 public 생성자 대신에 사용되는 static 방법이다 factory pattern과 연관됩니다. newInstance() 방법이 static이 아닙니다. 이것은 코드를 유지하기 위해 당신을 뒤쫓는 사람들에게 혼란을 일으킬 것입니다.

  4. onCreate()newInstance()을 호출하고 새 프래그먼트 인스턴스를 만든 다음이를 버리십시오. 시간이 낭비됩니다.

따라서, 당신의 조각의 원래 인스턴스 (이 온 곳) getSelectedIndex()NullPointerException을 설명 할 것이라고, 인수를 Bundle 설정이없는 가정.

임은 staticnewInstance() 방법을 사용하여 새로 만든 조각에 매개 변수를 전달하려면 조각

에 FragmentActivity에서 매개 변수를 전달하기 위해 노력하고 인수 Bundle새를 만들 때 조각은 완벽하게 타당합니다.

이미 존재하는 단편에 매개 변수를 전달하려면 해당 단편에 대해 일부 설정 메소드를 호출하십시오.

+0

가이드를 보내 주셔서 감사합니다. 문제를 해결하면 작업을 수행하고 답변을 업데이트 할 것입니다. – virtualpathum