应用程序在启动新活动时崩溃

时间:2013-12-17 23:26:33

标签: java android android-intent android-fragments android-bluetooth

我正在使用幻灯片片段开发应用。一切正常,应用程序启动没有问题。 View.onClickListener中出现问题。这是我的单个片段部分的代码:

 public static class ReceiveSectionFragment extends Fragment {

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
     View rootView = inflater.inflate(R.layout.receive, container, false);
         rootView.findViewById(R.id.bt_server_start)
         .setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
         Intent intent = new Intent(getActivity(), Receive.class);
         startActivity(intent);
                }
            });

        return rootView;
        }
    }

滑动到目标布局 - R.layout.receive效果很好。所以这里没问题。在R.id.bt_server_start按钮上单击下面的课程:

package com.receive.bluereceive;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

public class Receive extends Activity {

/**
 * Default Serial-Port UUID
 */
private String myUUID = "00001101-0000-1000-8000-00805F9B34FB";

/**
 * Default Bluetooth adapter on the device.
 */
private final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

/**
 * Magic number used in the Bluetooth enabling request.
 */
public final int REQUEST_ENABLE_BT = 2;

/**
 * The Server thread.
 */
private AcceptThread DeviceServer;

private NotificationCenter mNotificationCenter;

public final static String EXTRA_MESSAGE = "com.receive.intent.MESSAGE";

public final int BT_ENABLE_TIME = 35;

public final int BT_TIME_BTTIME = 1000 * BT_ENABLE_TIME;

public CountDownTimer BTCountDown;

public CountDownTimer MoveHistoryCountDown;

@Override
protected void onStart() {
    super.onStart();
    mNotificationCenter = new NotificationCenter();
    /*
     * Code responsible for calling method NotificationCenter() to print the incoming text to TextView field
     */
    registerReceiver(mNotificationCenter, new IntentFilter(EXTRA_MESSAGE));     
    /*
    * Start server on device
    */
    ServerThread();
    ((Button) findViewById(R.id.bt_server_start)).setEnabled(false);
    ((Button) findViewById(R.id.bt_server_stop)).setEnabled(true);
}

public void ServerThread() {
    DeviceServer = new AcceptThread();
    DeviceServer.start();
}

private class AcceptThread extends Thread {
    /*
     * That TAG will appear in the log in Eclipse
     */
    private final String ACC_TAG = AcceptThread.class.getName();
    /*
     * Bluetooth server socket
     */
    private final BluetoothServerSocket mServerSocket;

    public AcceptThread() {
        /*
         * Use a temporary object that is later assigned to mServerSocket, because mServerSocket is final
         */
        BluetoothServerSocket tmp = null;
        try {
            /*
             * MY_UUID is the app's UUID string, also used by the client code
             */
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(ACC_TAG, UUID.fromString(myUUID));
        } catch (IOException e) { }
        mServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;

        /*
         * Keep listening until exception occurs or a socket is returned
         */
        while (true) {
            try {
                Log.i(ACC_TAG,"Listening for a connection nearby...");
                socket = mServerSocket.accept();
                Log.i(ACC_TAG, "Connected to " + socket.getRemoteDevice().getName());
            } catch (IOException e) {
                break;
            }
            /*
             * If connection was accepted then proceed with code below
             * If Bluetooth socket does not equal null proceed with string reading as know script knows that device is connected
             * And if it is first ServerThread start, 
             */
            if (socket != null) {

                try {
                    String message;
                    DataInputStream incoming = new DataInputStream(socket.getInputStream());
                    message = incoming.readUTF();

                    Intent actual = new Intent(EXTRA_MESSAGE);
                    actual.putExtra("Message", String.format("%s",message));
                    getBaseContext().sendBroadcast(actual);


                } catch (IOException e) {
                    Log.e(ACC_TAG, "Error obtaining InputStream from socket");
                    e.printStackTrace();
                }
                try {
                    mServerSocket.close();
                } catch (IOException e) { }
                break;
            }
        }
    }

    /*
     * Will cancel the listening socket, and cause the thread to finish 
    */
    public void cancel() {
        try {
            mServerSocket.close();
        } catch (IOException e) { }
    }
}

private Vibrator getVibrator() {
    return (Vibrator) getSystemService(VIBRATOR_SERVICE);
}

/*
 * NOTIFICATION CLASS, PRINTS THE RECEIVED MESSAGE
 */
public class NotificationCenter extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if(intent.getAction().equals(EXTRA_MESSAGE)) {

            int counter = 0;
            ArrayList<String> historiaAL = new ArrayList<String>();
            historiaAL.add(intent.getExtras().getString("Message"));

            TextView actual = (TextView)findViewById(R.id.received_string);
            actual.setText(historiaAL.get(counter));

            TextView history = (TextView)findViewById(R.id.history_string);             
            String[] historiaA = historiaAL.toArray(new String[historiaAL.size()]);

            for(int i = 0; i < historiaAL.size(); i++)
            {
                history.append(historiaA[i]);
                history.append(" \n ");
            }


            getVibrator().vibrate(500);
            MoveHistoryCountDown = new HistoryMove(5000,5);
            MoveHistoryCountDown.start();
            counter++;
        } 
    }

}
public class HistoryMove extends CountDownTimer {
      public HistoryMove (long startTime, long interval) {
       super(startTime, interval);
      }

      @Override
      public void onFinish() {
          TextView recent = (TextView)findViewById(R.id.received_string);
          recent.setText(" ");
      }

      @Override
      public void onTick(long millisUntilFinished) {

      }
}
}

所有内容都包含在Manifest.xml中。我从LogCat得到的是:

12-18 00:36:14.136: E/AndroidRuntime(29672): FATAL EXCEPTION: main
12-18 00:36:14.136: E/AndroidRuntime(29672): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.receive.bluereceive/com.receive.bluereceive.Receive}: java.lang.NullPointerException
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.app.ActivityThread.access$600(ActivityThread.java:153)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.os.Looper.loop(Looper.java:137)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.app.ActivityThread.main(ActivityThread.java:5227)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at java.lang.reflect.Method.invokeNative(Native Method)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at java.lang.reflect.Method.invoke(Method.java:511)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at dalvik.system.NativeStart.main(Native Method)
12-18 00:36:14.136: E/AndroidRuntime(29672): Caused by: java.lang.NullPointerException
12-18 00:36:14.136: E/AndroidRuntime(29672):    at com.receive.bluereceive.Receive.onStart(Receive.java:68)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.app.Activity.performStart(Activity.java:5114)
12-18 00:36:14.136: E/AndroidRuntime(29672):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2271)
12-18 00:36:14.136: E/AndroidRuntime(29672):    ... 11 more

可能这是一个新手的错误,但仍然是一个小时,我仍然无法解决这个问题。

请不要降级声誉,我真的不能让它工作,即使它看起来似乎微不足道。

编辑:完整的主要代码 - http://pastebin.com/e4dyW8Th

1 个答案:

答案 0 :(得分:2)

我没有在您的活动中的任何地方看到setContentView,这意味着findViewById会返回null。

在您的活动中添加onCreate方法,并致电setContentView设置您的布局。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity);
}