Intent extra不会发送正确的结果

时间:2014-03-15 14:16:13

标签: android android-intent fragment

以下示例摘自BigNerdRanch Android手册第10章。 当我的犯罪列表片段启动犯罪片段时,通过额外检索的id与犯罪列表片段中的ID不同。这会产生空指针异常。另外,在crimelab中,我有一个if条件的登录但是永远不会被记录,这意味着if条件永远不会成立。有人可以帮我这个。

public class CrimeListFragment extends ListFragment {
..
    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        Crime c= ((CrimeAdapter)getListAdapter()).getItem(position);
        Intent i = new Intent(getActivity(), CrimeActivity.class);
        Log.d(TAG, c.getmTitle() + " " + c.getmId());
        i.putExtra(CrimeFragment.EXTRA_CRIME_ID, c.getmId());
        startActivity(i);
    }
..
}

public class CrimeFragment extends Fragment {
..
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UUID crimeId = (UUID)getActivity().getIntent().getSerializableExtra(EXTRA_CRIME_ID);
                //mCrime = new Crime();
        Log.d(TAG, CrimeLab.get(getActivity()).getCrime(crimeId).getmTitle());
        df = DateFormat.getDateInstance();
    }
..
}

public class CrimeLab {
.. 
       public Crime getCrime(UUID id){
        for (Crime c:mCrimes){          
            if (c.getmId() == id)
                Log.d(TAG, c.getmTitle());
                return c;
        }
        return null;

    }
..
}
  

03-14 18:30:33.649:D / CrimeListFragment(2162):犯罪#2   0bf14f8e-8527-4eae-a5a0-c8a19709a4df 03-14 18:30:33.729:   D / CrimeFragment(2162):犯罪#0

1 个答案:

答案 0 :(得分:0)

嗨,我遇到了同样的问题,花了几个小时来解决它,但现在它开始工作,修复了一些愚蠢的错误 尝试比较方法

  

public void onListItemClick(ListView l,View v,int position,long id)       {           //犯罪c =(犯罪)(getListAdapter())。getItem(position);           犯罪c =((CrimeAdapter)getListAdapter())。getItem(position);           //Log.d(TAG,c.getTitle()+"被点击");

    //Start Crime Activity
   Intent i = new Intent(getActivity(),CrimeActivity.class);
   i.putExtra(CrimeFragment.EXTRA_CRIME_ID,c.getId());
   startActivity(i);

}
     

public void onCreate(Bundle savedInstanceState)       {

   super.onCreate(savedInstanceState);
  //mCrime = new Crime();
  UUID crimeId = (UUID)getActivity().getIntent().getSerializableExtra(EXTRA_CRIME_ID);
  //UUID crimeId = (UUID)getActivity().getIntent().getExtras().getSerializable(EXTRA_CRIME_ID);
 mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);


}
     

public Crime getCrime(UUID id){           for(Crime c:mCrimes){               if(c.getId()。equals(id))                   返回c;           }       return null;       }