2013-08-20 73 views
1

我有一個相當簡單的程序,我正在玩碎片。它由一個活動(ComponentsActivity)組成,它在縱向視圖中有一個片段(ComponentsFragment)。切換到橫向時,ComponentsFragment保留在屏幕的左側,ArticleFragment添加到右側。當以縱向模式開始時,一切都起作用,並且切換到橫向模式也適用,但在橫向模式下嘗試切換回肖像會導致ArticleFragment的OnActivityCreated方法中出現空指針異常。我不確定爲什麼這個方法甚至被稱爲活動應該用單個ComponentsFragment重新創建自己。在片段OnActivityCreated方法中的Android空指針異常

下面是活動代碼:

package com.cab.apitesting; 

import android.content.res.Configuration; 
import android.os.Bundle; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentTransaction; 
import android.view.View; 

public class ComponentsActivity extends FragmentActivity implements ComponentsFragment.OnArticleSelectedListener { 
    boolean mDualPane; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_components); 

     View articleContainer = findViewById(R.id.article_container); 
     mDualPane = articleContainer != null && articleContainer.getVisibility() == View.VISIBLE; 

     FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
     transaction.add(R.id.fragment_container, ComponentsFragment.newInstance()); 
     transaction.commit(); 

     if (mDualPane) { 
      FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction(); 
      transaction2.add(R.id.article_container, ArticleFragment.newInstance(1)); 
      transaction2.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
      transaction2.addToBackStack(null); 
      transaction2.commit(); 
     } 
    } 

    @Override 
    public void onArticleSelected(int id) { 
     int articleIndex = 0; 

     switch (id) { 
      case R.id.button_article_one: 
       articleIndex = 1; 
       break; 
      case R.id.button_article_two: 
       articleIndex = 2; 
       break; 
      case R.id.button_article_three: 
       articleIndex = 3; 
       break; 
      default: 
       break; 
     } 

     if (mDualPane) { 
      FragmentTransaction transaction3 = getSupportFragmentManager().beginTransaction(); 
      transaction3.add(R.id.article_container, ArticleFragment.newInstance(articleIndex)); 
      transaction3.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
      transaction3.commit(); 
     } else { 
      FragmentTransaction transaction3 = getSupportFragmentManager().beginTransaction(); 
      transaction3.replace(R.id.fragment_container, ArticleFragment.newInstance(articleIndex)); 
      transaction3.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
      transaction3.addToBackStack(null); 
      transaction3.commit(); 
     } 
    } 
} 

這裏是ComponentsFragment代碼:

package com.cab.apitesting; 

import android.app.Activity; 
import android.content.ContentUris; 
import android.content.Intent; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.provider.ContactsContract; 
import android.support.v4.app.Fragment; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.TextView; 

public class ComponentsFragment extends Fragment { 
    Button artOneButton; 
    Button artTwoButton; 
    Button artThreeButton; 

    OnArticleSelectedListener mArticleListener; 

    public static ComponentsFragment newInstance() { 
     ComponentsFragment f = new ComponentsFragment(); 
     Bundle args = new Bundle(); 
     f.setArguments(args); 

     return f; 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 

     try { 
      mArticleListener = (OnArticleSelectedListener) activity; 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener"); 
     } 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment_components, container, false); 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 

     artOneButton = (Button)getView().findViewById(R.id.button_article_one); 
     artOneButton.setOnClickListener(onClick); 

     artTwoButton = (Button)getView().findViewById(R.id.button_article_two); 
     artTwoButton.setOnClickListener(onClick); 

     artThreeButton = (Button)getView().findViewById(R.id.button_article_three); 
     artThreeButton.setOnClickListener(onClick); 
    } 

    private View.OnClickListener onClick = new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent; 

      switch (view.getId()) { 
       case R.id.button_article_one: 
       case R.id.button_article_two: 
       case R.id.button_article_three: 
        mArticleListener.onArticleSelected(view.getId()); 
        break; 
       default: 
        break; 
      } 
     } 
    }; 

    public interface OnArticleSelectedListener { 
     public void onArticleSelected(int id); 
    } 
} 

這裏是ArticleFragments代碼:

package com.cab.apitesting; 

import android.content.res.Configuration; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.TextView; 

public class ArticleFragment extends Fragment { 
    private static String[] articles = { 
      "Bacon ipsum dolor sit amet ribeye nulla labore cow. Reprehenderit meatball pork belly non, laborum commodo tail. Aliquip nulla ad ham hock. Sausage swine jerky nulla consectetur in voluptate short loin ham hock tempor. Ball tip tenderloin excepteur strip steak in. Incididunt pork chop dolor, nisi short ribs ex mollit proident consequat.\n" + 
        "\n" + 
        "Velit sirloin doner brisket leberkas andouille elit rump. Cow est pariatur fugiat. Culpa shankle jowl andouille. Chuck beef ribs fatback ut, aliquip duis doner aute.\n" + 
        "\n" + 
        "T-bone consectetur filet mignon dolore beef ribs mollit, tenderloin esse tempor leberkas labore meatloaf ball tip. Jerky filet mignon meatloaf, officia pastrami voluptate beef drumstick capicola aute chuck shoulder venison short ribs. Fugiat ad enim venison, frankfurter rump beef ribs pancetta. Duis laborum in corned beef dolor in. Ball tip leberkas esse, pariatur commodo bacon jerky jowl pancetta bresaola tongue minim aliqua t-bone meatloaf. Ham sint tongue ut sunt pig culpa anim beef sirloin do. Irure jerky dolore tenderloin ball tip mollit ham hock, boudin eiusmod cow exercitation strip steak in filet mignon.\n" + 
        "\n" + 
        "Deserunt veniam meatloaf cupidatat meatball chicken sed qui cow consectetur filet mignon. Ad officia adipisicing, pig biltong nostrud nulla sirloin in sausage velit. Ut laborum meatloaf, tail exercitation consectetur officia fatback sirloin. Venison incididunt strip steak ham, sint ut pancetta cupidatat aliquip eiusmod in officia leberkas filet mignon. Beef ribs laborum kielbasa mollit boudin beef. Tri-tip ball tip pig nulla dolor ut pork chop aliqua corned beef sirloin t-bone. Ea adipisicing elit turkey velit id.\n" + 
        "\n" + 
        "Shank leberkas dolore pork chop nostrud qui short loin. Commodo ad ex aute proident elit filet mignon qui aliqua laborum kielbasa beef ribs ball tip labore. Voluptate laboris ut biltong incididunt corned beef. Ham hock kielbasa bresaola, shankle sint eu in reprehenderit minim excepteur frankfurter id sirloin commodo ut.", 
      "Your bones don't break, mine do. That's clear. Your cells react to bacteria and viruses differently than mine. You don't get sick, I do. That's also clear. But for some reason, you and I react the exact same way to water. We swallow it too fast, we choke. We get some in our lungs, we drown. However unreal it may seem, we are connected, you and I. We're on the same curve, just on opposite ends.\n" + 
        "\n" + 
        "Look, just because I don't be givin' no man a foot massage don't make it right for Marsellus to throw Antwone into a glass motherfuckin' house, fuckin' up the way the nigger talks. Motherfucker do that shit to me, he better paralyze my ass, 'cause I'll kill the motherfucker, know what I'm sayin'?\n" + 
        "\n" + 
        "Now that we know who you are, I know who I am. I'm not a mistake! It all makes sense! In a comic, you know how you can tell who the arch-villain's going to be? He's the exact opposite of the hero. And most times they're friends, like you and me! I should've known way back when... You know why, David? Because of the kids. They called me Mr Glass.\n" + 
        "\n" + 
        "Your bones don't break, mine do. That's clear. Your cells react to bacteria and viruses differently than mine. You don't get sick, I do. That's also clear. But for some reason, you and I react the exact same way to water. We swallow it too fast, we choke. We get some in our lungs, we drown. However unreal it may seem, we are connected, you and I. We're on the same curve, just on opposite ends.\n" + 
        "\n" + 
        "Do you see any Teletubbies in here? Do you see a slender plastic tag clipped to my shirt with my name printed on it? Do you see a little Asian child with a blank expression on his face sitting outside on a mechanical helicopter that shakes when you put quarters in it? No? Well, that's what you see at a toy store. And you must think you're in a toy store, because you're here shopping for an infant named Jeb.", 
      "Tomorrow vee come back und cut off your chonson. Dolor sit amet, consectetur adipiscing elit. And I'm talkin' about the Dude here —sometimes there's a man who, wal, he's the man for his time'n place, he fits right in there—and that's the Dude, in Los Angeles. Praesent ac magna justo pellentesque ac. This guy fucking walks. I've never been more certain of anything in my life. Lectus quis elit blandit fringilla a ut turpis praesent felis ligula, malesuada suscipit.\n" + 
        "\n" + 
        "Does the Pope shit in the woods? Malesuada non, ultrices non urna sed. Well sir, it's this rug I have, really tied the room together. Orci ipsum, placerat id condimentum rutrum, rhoncus ac lorem aliquam. Who's in pyjamas, Walter? Placerat posuere neque, at dignissim magna ullamcorper in aliquam sagittis massa ac. Dude, please!… Is this your homework, Larry? Tortor ultrices faucibus curabitur eu mi sapien, ut.\n" + 
        "\n" + 
        "It's a complicated case, Maude. Lotta ins, lotta outs, lotta what-have-yous. Ultricies ipsum morbi eget risus nulla nullam vel nisi enim, vel auctor. Walter, this isn't a First Amendment thing. Ante morbi id urna vel felis. Fuckin' A. Lacinia placerat vestibulum turpis nulla, viverra nec. Nihilists! Jesus. Volutpat ac, ornare id lectus cras pharetra faucibus tristique nullam. Look, I've got certain information, certain things have come to light, and uh, has it ever occurred to you, man, that given the nature of all this new shit, that, uh, instead of running around blaming me, that this whole thing might just be, not, you know, not just such a simple, but uh—you know? Non accumsan justo nulla facilisi integer interdum elementum nulla, nec eleifend nisl euismod.\n" + 
        "\n" + 
        "No, the, uh, police chief of Malibu. A real reactionary. Ac maecenas vitae eros velit, eu suscipit. Vee belief in nossing, Lebowski! Erat integer purus lacus, pretium vel venenatis eu, volutpat non erat donec. Come and get it. Fucking nihilist. A metus ac eros dictum aliquet nulla consectetur egestas placerat maecenas pulvinar nisl et. They finally did it. They killed my fucking car. Nisl rhoncus at volutpat felis blandit in libero turpis, laoreet et molestie.\n" + 
        "\n" + 
        "Is this your homework, Larry? Sed, volutpat et erat. Come on, Donny, they were threatening castration! Nulla ut orci quis. Another Caucasian, Gary. Neque consectetur tincidunt aliquam erat volutpat donec aliquam orci. I got information—new shit has come to light and—shit, man! She kidnapped herself! Eget mi lobortis sed tincidunt diam mattis fusce. They're nihilists. Sem quam, ultricies sed convallis ac, hendrerit eu urna curabitur varius egestas nibh." 
    }; 

    public static ArticleFragment newInstance(int index) { 
     ArticleFragment f = new ArticleFragment(); 
     Bundle args = new Bundle(); 
     args.putInt("index", index); 
     f.setArguments(args); 

     return f; 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.fragment_article, container, false); 
    } 

    @Override 
public void onActivityCreated(Bundle savedInstanceState) { 
    super.onActivityCreated(savedInstanceState); 

    TextView article = (TextView)getActivity().findViewById(R.id.textview_article); 
    int index = getArguments().getInt("index"); 
    article.setText(articles[index - 1]); 
} 
} 

以下是錯誤日誌:

08-20 15:35:58.214 1328-1328/com.cab.apitesting E/AndroidRuntime: FATAL EXCEPTION: main 
     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cab.apitesting/com.cab.apitesting.ComponentsActivity}: java.lang.NullPointerException 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
     at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3692) 
     at android.app.ActivityThread.access$700(ActivityThread.java:141) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240) 
     at android.os.Handler.dispatchMessage(Handler.java:99) 
     at android.os.Looper.loop(Looper.java:137) 
     at android.app.ActivityThread.main(ActivityThread.java:5041) 
     at java.lang.reflect.Method.invokeNative(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:511) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
     at dalvik.system.NativeStart.main(Native Method) 
     Caused by: java.lang.NullPointerException 
     at com.cab.apitesting.ArticleFragment.onActivityCreated(ArticleFragment.java:62) 
     at android.support.v4.app.Fragment.performStart(Fragment.java:1484) 
     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:941) 
     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088) 
     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1070) 
     at android.support.v4.app.FragmentManagerImpl.dispatchStart(FragmentManager.java:1866) 
     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:568) 
     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164) 
     at android.app.Activity.performStart(Activity.java:5114) 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153) 
     ... 12 more 

,導致該錯誤的代碼行是:

article.setText(articles[index - 1]); 
在ArticleFragment類

。我假設這是失敗的,因爲文章變量爲空(因爲它應該是因爲當應用程序處於縱向模式時ArticleFragment不應該存在)。但是爲什麼OnActivityCreated方法在應該不存在的片段中被調用?

+0

那,活動重新更換。一旦該活動創建完成後,隨着每個片段偵聽此api,就會調用創建的Activity上的片段,以便開發人員可以修改該特定行爲的行爲。 – Ahmed

+0

我可以看到的另一件事是您正在嘗試獲取活動佈局文本視圖。你可以請嘗試評論你的onActivityCreated方法。 – Ahmed

+0

這是我在想什麼,但那我該怎麼防止呢?切換屏幕方向時,我能否以某種方式「殺死」該片段? – user2700452

回答

4

不此線..

TextView article = (TextView)getActivity().findViewById(R.id.textview_article); 

用,因爲在每個取向變化..
TextView article = (TextView)getView().findViewById(R.id.textview_article);

+0

修正了它 - 你能解釋爲什麼這個工作嗎? – user2700452

+0

,因爲getActivity會返回沒有佈局的活動 –

+0

雖然切換到橫向時它的工作方式是如此。原始行返回了對正確元素的引用,並且填充了正確的文本。切換回肖像後,它纔會停止工作。你的解決方案明確解決了這個問題,但是我仍然在努力解決爲什麼它在使用一個方向時會起作用,但是當切換到另一個方向時會崩潰.... – user2700452