2014-02-09 66 views
0

我試着用3個片段java代碼不片段活動工作

當我嘗試輸入片段類中的Java代碼創建Android平臺的應用程序,我一直這個錯誤: java.lang.NullPointerException

例如,對於一個簡單的按鈕來改變視圖:

package com.test; 



import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentTransaction; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.Button; 

public class creation extends Fragment { 


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

     View root = inflater.inflate(R.layout.creation, container, false); 

     final Button ok = (Button)getView(). findViewById(R.id.button3); 
     ok.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // Create new fragment and transaction 
       Fragment newFragment = new mesvideos(); 
       // consider using Java coding conventions (upper char class names!!!) 
       FragmentTransaction transaction = getFragmentManager().beginTransaction(); 

       // Replace whatever is in the fragment_container view with this fragment, 
       // and add the transaction to the back stack 
       transaction.replace(R.layout.creation, newFragment); 
       transaction.addToBackStack(null); 

       // Commit the transaction 
       transaction.commit(); 


     } 
    }); 
return root ; 
} 

或者與VideoView

mVideoView = (VideoView) findViewById(R.id.videoView1); 
      mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + 
         "/" + R.raw.presentation)); 
      mVideoView.setMediaController(new MediaController(this)); 
      mVideoView.requestFocus(); 
+0

粘貼完整的堆棧跟蹤(複製logcat中存在錯誤的部分) –

+0

錯誤告訴您它發生的確切路線。所有案例中有99%在該行中有一個「。」。 '.'之前的東西是'null'。在你的情況'getView()' – zapl

回答

3

並非只是說您遇到NullPointerException,請指定完整的堆棧跟蹤或告訴我們您的代碼在哪一行出現NPE。

FWIW,你

final Button ok = (Button)getView(). findViewById(R.id.button3); 

也許應該

final Button ok = (Button) root.findViewById(R.id.button3); 

我懷疑,因爲你纔剛剛創建的根視圖,並沒有返回/設置它,getView()將返回null

PS。你的班級名稱「創造」是非標準的。 Java類名應該以大寫字母開頭,如果您的類擴展了Fragment,那麼通常讓類名以「Fragment」結尾。例如:「CreationFragment」。