Question

I have begun trying to learn how to program on the android platform, and I made this program that is supposed to communicate to a Bluetooth module. However, every time I launch it, it crashes immediately, and responds with unfortunately, "program name" has stopped working. What's wrong?

Main Activity
    package com.example.enge1104;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
    TextView myLabel;
    Button buttonLeft;
    Button buttonRight;




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


        buttonLeft = (Button)findViewById(R.id.buttonLeft);
        buttonRight = (Button)findViewById(R.id.buttonRight);
        myLabel = (TextView)findViewById(R.id.display);


        buttonLeft.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    try {
                        sendData(0);
                    } catch (IOException e) {}
                    break;
                case MotionEvent.ACTION_UP:
                    try {
                        sendData(1);
                    } catch (IOException e) {}
                    break;
                }
                return false;
            }
        });

        buttonRight.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    try {
                        sendData(2);
                    } catch (IOException e) {}
                    break;
                case MotionEvent.ACTION_UP:
                    try {
                        sendData(3);
                    } catch (IOException e) {}
                    break;
                }
                return false;
            }
        });



        try 
        {
            findBT();
            openBT();
        }
        catch (IOException ex) { }

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }

    }


    void sendData( int newValue) throws IOException
    {
        mmOutputStream.write(newValue);
    }

    void findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
         if (!mBluetoothAdapter.isEnabled()) {
             Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBtIntent,0);
         }
         mmDevice = null;
         Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
      // If there are paired devices
      if (pairedDevices.size() > 0) {

          for (BluetoothDevice device : pairedDevices) {

             if(device.getName().equals("HC-06")) //Name of bluetooth module
              {
                  mmDevice = device;
                  break;
              }
          }
      }
    }

    void openBT() throws IOException
    {
         UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID

         mmSocket = null;       
            mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
            mmSocket.connect();
            mmOutputStream = mmSocket.getOutputStream();
            myLabel.setText("Bluetooth Opened");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

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

The XML file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.enge1104.MainActivity$PlaceholderFragment" >

    <Button
        android:id="@+id/buttonLeft"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginRight="46dp"
        android:layout_toLeftOf="@+id/buttonRight"
        android:text="@string/button_left" />

    <Button
        android:id="@+id/buttonRight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/buttonLeft"
        android:layout_alignBottom="@+id/buttonLeft"
        android:layout_alignParentRight="true"
        android:layout_marginRight="67dp"
        android:text="@string/button_right" />

    <TextView
        android:id="@+id/display"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp"
        android:text="@string/disDisplay" />

</RelativeLayout>

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ENGE1104</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="button_right">Right</string>
    <string name="button_left">Left</string>
    <string name="disDisplay">Not Connected</string>
</resources>

The manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.enge1104"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.enge1104.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

The log-cat

04-21 15:36:14.572: I/Process(25563): Sending signal. PID: 25563 SIG: 9
04-21 15:36:26.512: D/AndroidRuntime(25760): Shutting down VM
04-21 15:36:26.512: W/dalvikvm(25760): threadid=1: thread exiting with uncaught exception (group=0x41522ba8)
04-21 15:36:26.512: E/AndroidRuntime(25760): FATAL EXCEPTION: main
04-21 15:36:26.512: E/AndroidRuntime(25760): Process: com.example.enge1104, PID: 25760
04-21 15:36:26.512: E/AndroidRuntime(25760): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.enge1104/com.example.enge1104.MainActivity}: java.lang.NullPointerException
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.os.Handler.dispatchMessage(Handler.java:102)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.os.Looper.loop(Looper.java:136)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.app.ActivityThread.main(ActivityThread.java:5017)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at java.lang.reflect.Method.invokeNative(Native Method)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at java.lang.reflect.Method.invoke(Method.java:515)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at dalvik.system.NativeStart.main(Native Method)
04-21 15:36:26.512: E/AndroidRuntime(25760): Caused by: java.lang.NullPointerException
04-21 15:36:26.512: E/AndroidRuntime(25760):    at com.example.enge1104.MainActivity.onCreate(MainActivity.java:51)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.app.Activity.performCreate(Activity.java:5231)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-21 15:36:26.512: E/AndroidRuntime(25760):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-21 15:36:26.512: E/AndroidRuntime(25760):    ... 11 more
04-21 15:36:29.032: I/Process(25760): Sending signal. PID: 25760 SIG: 9
Was it helpful?

Solution

After realizing what I did incorrectly, that setContentView(R.layout.activity_main); was looking at the activity_main.xml for all of the , but my layout was actually in fragment_main.xml. Thus I moved the content within fragment_main.xml to activity_main.xml.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top