当我使用getArguments()时它显示错误(java.lang.NullPointerException)

时间:2013-12-25 08:29:04

标签: java android android-fragments

我有一个Activity,我希望它添加一个片段。

以下代码位于“活动”中。

package com.example.smartipcam;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import com.example.smartipcam.R;
import com.example.smartipcam.Mainplayer;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.provider.MediaStore.MediaColumns;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.FragmentManager.BackStackEntry;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Configuration;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.Window;
import android.view.MenuItem.OnMenuItemClickListener;

public class MainActivity extends Activity {

    private WifiManager wifiManager;

    public static String intToIp(int addr) {

        return ((addr & 0xFF) + "." + ((addr >>>= 8) & 0xFF) + "." + ((addr >>>= 8) & 0xFF) + "." + ((addr >>>= 8) & 0xFF)) ;
    }

    public static Uri addImageAsApplication(ContentResolver contentResolver, String name, long dateTaken,
            String directory, String filename) {

        String filePath = directory + File.separator + filename ;

        String[] imageProjection = new String[] { "DISTINCT " + BaseColumns._ID, MediaColumns.DATA,
                MediaColumns.DISPLAY_NAME } ;

        String imageSelection = new String(Images.Media.TITLE + "=? AND " + Images.Media.DISPLAY_NAME + "=?") ;

        String[] imageSelectionArgs = new String[] { name, filename } ;

        Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageProjection,
                imageSelection, imageSelectionArgs, null) ;

        if (cursor == null || cursor.getCount() == 0) {

            ContentValues values = new ContentValues(7) ;
            values.put(Images.Media.TITLE, name) ;
            values.put(Images.Media.DISPLAY_NAME, filename) ;
            values.put(Images.Media.DATE_TAKEN, dateTaken) ;
            values.put(Images.Media.MIME_TYPE, "image/jpeg") ;
            values.put(Images.Media.DATA, filePath) ;

            return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ;
        } else {

            int idColumn = cursor.getColumnIndex(MediaColumns._ID) ;

            if (idColumn == -1)
                return null ;

            cursor.moveToFirst() ;

            Long id = cursor.getLong(idColumn) ;

            return Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString() + "/"
                    + String.valueOf(id)) ;
        }
    }

    public static void addFragment(Fragment originalFragment, Fragment newFragment) {

        FragmentManager fragmentManager = originalFragment.getActivity().getFragmentManager() ;

        if (fragmentManager.getBackStackEntryCount() > 0) {

            FragmentManager.BackStackEntry backEntry = fragmentManager.getBackStackEntryAt(fragmentManager
                    .getBackStackEntryCount() - 1) ;

            if (backEntry != null && backEntry.getName().equals(newFragment.getClass().getName()))
                return ;
        }

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction() ;

        fragmentTransaction
                .setCustomAnimations(R.anim.right_in, R.anim.right_out, R.anim.left_in, R.anim.left_out)
                .replace(R.id.mainMainFragmentLayout, newFragment)
                .addToBackStack(newFragment.getClass().getName()).commit() ;
        fragmentManager.executePendingTransactions() ;

    }

    public static void backToFristFragment(Activity activity) {

        FragmentManager fragmentManager = activity.getFragmentManager() ;

        if (fragmentManager.getBackStackEntryCount() == 0)
            return ;

        BackStackEntry rootEntry = fragmentManager.getBackStackEntryAt(0) ;

        if (rootEntry == null)
            return ;

        int rootFragment = rootEntry.getId() ;
        fragmentManager.popBackStack(rootFragment, FragmentManager.POP_BACK_STACK_INCLUSIVE) ;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Log.i("Fragment Activity", "ON CREATE " + savedInstanceState) ;
        super.onCreate(savedInstanceState);

        if (sSelectedLocale == null) {

            sSelectedLocale = sDefaultLocale ;
        }

        Locale.setDefault(Locale.ENGLISH);
        Configuration config = new Configuration();
        config.locale= Locale.ENGLISH;
        getResources().updateConfiguration(config, null);

        sAppName = getResources().getString(R.string.app_name);

        Locale.setDefault(sSelectedLocale);
        config = new Configuration();
        config.locale = sSelectedLocale;
        getResources().updateConfiguration(config, null);

        sAppDir = Environment.getExternalStorageDirectory().getPath() + File.separator + sAppName;
        Log.i("Fragment Activity", sAppDir) ;
        File appDir = new File(sAppDir) ;
        if (!appDir.exists()) {
            appDir.mkdir() ;
        }

        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.activity_main);

        setTitle(getResources().getString(R.string.app_name)) ;

        getActionBar().setDisplayHomeAsUpEnabled(false) ;

        setProgressBarIndeterminateVisibility(false) ;

        if(savedInstanceState == null) {

            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE) ;

            Log.i("Wifi Info", wifiManager.getConnectionInfo().toString()) ;

            if (wifiManager.isWifiEnabled() && wifiManager.getConnectionInfo().getNetworkId() != -1) {

                FragmentManager fragmentManager = getFragmentManager() ;
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction() ;

                Mainplayer newFragment = Mainplayer.newInstance("mediaurl",true);

                Fragment fragment = new Mainplayer() ;
                fragmentTransaction.add(R.id.mainMainFragmentLayout, fragment) ;
                fragmentTransaction.commit() ;
            }
        }
    }   
}

以下代码在Fragment中。

package com.example.smartipcam;

import com.example.smartipcam.MainActivity;
import com.example.smartipcam.R;
import com.example.smartipcam.CameraCommand;
import com.example.smartipcam.VLCApplication;
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.ImageFormat;
import android.graphics.PixelFormat;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;


public class Mainplayer extends Fragment {

    public static final String DEFAULT_MJPEG_PUSH_URL = "/cgi-bin/liveMJPEG" ;
    public static final String DEFAULT_MJPEG_PULL_URL = "/cgi-bin/staticMJPEG" ;
    private static final String TAG = "MJPEG Player";
    private String mMediaUrl ;
    private boolean mPushMode ;
    private static final String KEY_MEDIA_URL = "mediaUrl" ;
    private static final String KEY_PUSH_MODE = "pushMode" ;
    private TextView curdate;
    private SurfaceView mSurface;
    private SurfaceHolder mSurfaceHolder;
    private FrameLayout mSurfaceFrame;


    public static Mainplayer newInstance(String mediaUrl, boolean pushMode) {
        // TODO Auto-generated constructor stub
        Mainplayer fragment = new Mainplayer();

        Bundle args = new Bundle();

        if (mediaUrl != null)
            args.putString(KEY_MEDIA_URL, mediaUrl) ;

        args.putBoolean(KEY_PUSH_MODE, pushMode) ;
        fragment.setArguments(args) ;

        return fragment ;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        Log.d(TAG, "Fragment Created") ;

        mMediaUrl = getArguments().getString(KEY_MEDIA_URL);
        mPushMode = getArguments().getBoolean(KEY_PUSH_MODE, false) ;

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        Log.d(TAG, "Fragment View Created") ;

        View view = inflater.inflate(R.layout.maiplayer, container, false) ;

        return view;
    }

}

----------------------------------------------- ---------- logcat的

E/AndroidRuntime(17635): FATAL EXCEPTION: main
E/AndroidRuntime(17635): java.lang.NullPointerException
E/AndroidRuntime(17635):    at com.example.smartipcam.Mainplayer.onCreate(Mainplayer.java:81)
E/AndroidRuntime(17635):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:800)
E/AndroidRuntime(17635):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1039)
E/AndroidRuntime(17635):    at android.app.BackStackRecord.run(BackStackRecord.java:635)
E/AndroidRuntime(17635):    at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1405)
E/AndroidRuntime(17635):    at android.app.FragmentManagerImpl$1.run(FragmentManager.java:430)
E/AndroidRuntime(17635):    at android.os.Handler.handleCallback(Handler.java:615)
E/AndroidRuntime(17635):    at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(17635):    at android.os.Looper.loop(Looper.java:213)
E/AndroidRuntime(17635):    at android.app.ActivityThread.main(ActivityThread.java:4786)
E/AndroidRuntime(17635):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(17635):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(17635):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
E/AndroidRuntime(17635):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
E/AndroidRuntime(17635):    at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager(  568):   Force finishing activity com.example.smartipcam/.MainActivity

错误发生似乎我没有调用newInstance。 我不知道在哪里可以调用newInstance?

1 个答案:

答案 0 :(得分:1)

使用以下

FragmentManager fragmentManager = getFragmentManager() ;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction() ;
MainPlayer newFragment = Mainplayer.newInstance("mediaurl",true/false);
fragmentTransaction.show(newFragment );