• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Bluetooth app (Multiple Fragments)

Kito312

Lurker
Apr 21, 2015
5
0
I am building an application that is used to control a robot via bluetooth. I have a problem of connecting my app with the bluetooth module. Whenever, I open the app, it crashes.

Explanation of the app:
* The app contains 3 main fragments:
1) 2 Fragment that has buttons and used to send data to the bluetooth module
2) 1 Fragment that receive data from the bluetooth module and display data on the android app
* I created a bluetooth communication class that is quite similar to: http://developer.android.com/guide/topics/connectivity/bluetooth.html
* I called onResume and onPause on each fragmet but that didn't work.

Can someone please help me fix the code? I will post the code, no worries :D

Code:

Fragment 1:
Java:
package com.example.ibm.exoskeleton_2;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
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.Button;

import java.io.IOException;

public class ExtraExercise extends Fragment {

    Button start4,start5,start6,start7;
    Button play4,play5,play6,play7;
    Button stop4,stop5,stop6,stop7;
    BluetoothCommunication BC = new BluetoothCommunication();
    BluetoothCommunication.ConnectedThread mConnectedThread;
    BluetoothAdapter btAdapter = BC.getBtAdapter();
    BluetoothSocket btSocket = BC.getBtSocket();
    @override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        BC.btAdapter.enable();
        try {
            BC.btSocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        View rootView = inflater.inflate(R.layout.extraxercise, container, false);
        start4 = (Button) rootView.findViewById(R.id.Start4Button);
        start5 = (Button) rootView.findViewById(R.id.Start5Button);
        start6 = (Button) rootView.findViewById(R.id.Start6Button);
        start7 = (Button) rootView.findViewById(R.id.Start7Button);
        play4 = (Button) rootView.findViewById(R.id.Video4Button);
        play5 = (Button) rootView.findViewById(R.id.Video5Button);
        play6 = (Button) rootView.findViewById(R.id.Video6Button);
        play7 = (Button) rootView.findViewById(R.id.Video7Button);
        stop4 = (Button) rootView.findViewById(R.id.Stop4Button);
        stop5 = (Button) rootView.findViewById(R.id.Stop5Button);
        stop6 = (Button) rootView.findViewById(R.id.Stop6Button);
        stop7 = (Button) rootView.findViewById(R.id.Stop7Button);
            btAdapter = BluetoothAdapter.getDefaultAdapter();        // get Bluetooth adapter
            BC.checkBTState();

            start4.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    start4.setEnabled(true);

                    mConnectedThread.write("4");    // Send "4" via Bluetooth
                }
            });
            start5.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    start5.setEnabled(true);
                    mConnectedThread.write("5");    // Send "4" via Bluetooth
                }
            });
            start6.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    start6.setEnabled(true);
                    mConnectedThread.write("6");    // Send "4" via Bluetooth
                }
            });
            start7.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    start7.setEnabled(true);
                    mConnectedThread.write("7");    // Send "4" via Bluetooth
                }
            });
            stop4.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    stop4.setEnabled(true);
                    mConnectedThread.write("0");    // Send "4" via Bluetooth
                }
            });
            stop5.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    stop5.setEnabled(true);
                    mConnectedThread.write("0");    // Send "4" via Bluetooth
                }
            });
            stop6.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    stop6.setEnabled(true);
                    mConnectedThread.write("0");    // Send "4" via Bluetooth
                }
            });
            stop7.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    stop7.setEnabled(true);
                    mConnectedThread.write("0");    // Send "4" via Bluetooth
                }
            });
        return rootView;
    }


}
Fragment 2:
Java:
package com.example.ibm.exoskeleton_2;

import android.bluetooth.BluetoothAdapter;
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.Button;

import java.io.IOException;

/**
* Created by IBM on 07-Apr-15.
*/
public class MainPage extends Fragment {
    Button start1,start2,start3;
    Button play1,play2,play3;
    Button stop1,stop2,stop3;
    Button tour;
    BluetoothCommunication BC = new BluetoothCommunication();
    BluetoothCommunication.ConnectedThread mConnectedThread;
    BluetoothAdapter btAdapter = BC.getBtAdapter();
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        BC.btAdapter.enable();
        try {
            BC.btSocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        View rootView = inflater.inflate(R.layout.main_page, container, false);
        start1 = (Button) rootView.findViewById(R.id.Start1Button);
        start2 = (Button) rootView.findViewById(R.id.Start2Button);
        start3 = (Button) rootView.findViewById(R.id.Start3Button);
        play1 = (Button) rootView.findViewById(R.id.Video1Button);
        play2 = (Button) rootView.findViewById(R.id.Video2Button);
        play3 = (Button) rootView.findViewById(R.id.Video3Button);
        stop1 = (Button) rootView.findViewById(R.id.Stop1Button);
        stop2 = (Button) rootView.findViewById(R.id.Stop2Button);
        stop3 = (Button) rootView.findViewById(R.id.Stop3Button);
        tour = (Button) rootView.findViewById(R.id.TourButton);
        return rootView;
    }
    public class ControllerFragment extends Fragment implements View.OnClickListener {
        @override

        public void onClick(View v) {
            btAdapter = BluetoothAdapter.getDefaultAdapter();        // get Bluetooth adapter
            BC.checkBTState();

            start1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    start1.setEnabled(true);
                    mConnectedThread.write("1");    // Send "4" via Bluetooth
                }
            });
            start2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    start2.setEnabled(true);
                    mConnectedThread.write("2");    // Send "4" via Bluetooth
                }
            });
            start3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    start3.setEnabled(true);
                    mConnectedThread.write("3");    // Send "4" via Bluetooth
                }
            });

            stop1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    stop1.setEnabled(true);
                    mConnectedThread.write("0");    // Send "4" via Bluetooth
                }
            });
            stop2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    stop2.setEnabled(true);
                    mConnectedThread.write("0");    // Send "4" via Bluetooth
                }
            });
            stop3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    stop3.setEnabled(true);
                    mConnectedThread.write("0");    // Send "4" via Bluetooth
                }
            });

        }
    }

}
Fragment 3:
Java:
package com.example.ibm.exoskeleton_2;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by IBM on 07-Apr-15.
*/
public class OnYourOwn extends android.support.v4.app.Fragment {
    EditText thumb,index,middle,ring,pinky;
    Handler  h;
    final int RECIEVE_MESSAGE = 1;        // Status  for Handler
    private StringBuilder sb = new StringBuilder();
    static int check = 1;
    BluetoothCommunication BC = new BluetoothCommunication();
    BluetoothCommunication.ConnectedThread mConnectedThread;
    BluetoothAdapter btAdapter = BC.getBtAdapter();
    BluetoothSocket btSocket = BC.getBtSocket();
    // Get the input and output streams, using temp objects because
    // member streams are final

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        BC.btAdapter.enable();
        try {
            BC.btSocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        View rootView = inflater.inflate(R.layout.try_your_own, container, false);
        thumb = (EditText) rootView.findViewById(R.id.ThumbText);
        index = (EditText) rootView.findViewById(R.id.IndexText);
        middle = (EditText) rootView.findViewById(R.id.MiddleText);
        ring = (EditText) rootView.findViewById(R.id.RingText);
        pinky = (EditText) rootView.findViewById(R.id.PinkyText);
         h = new Handler() {
            public void handleMessage(android.os.Message msg) {
                switch (msg.what) {
                    case RECIEVE_MESSAGE:                                                    // if receive massage
                        byte[] readBuf = (byte[]) msg.obj;
                        String strIncom = new String(readBuf, 0, msg.arg1);                    // create string from bytes array
                        sb.append(strIncom);                                                // append string
                        int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                        if (endOfLineIndex > 0) {                                             // if end-of-line,
                            String sbprint = sb.substring(0, endOfLineIndex);                // extract string
                            sb.delete(0, sb.length());                                        // and clear
                            if (check == 1)
                            thumb.setText(sbprint);                                     // update thumb
                            else if (check == 2)
                                index.setText(sbprint);
                            else if (check == 3)
                                middle.setText(sbprint);
                            else if (check == 4)
                                ring.setText(sbprint);
                            else
                                pinky.setText(sbprint);
                        }
                        // Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                        break;
                }
            };
        };
        return rootView;
    }
    public class ControllerFragment extends android.support.v4.app.Fragment {
        public void onClick(View v) {
            btAdapter = BluetoothAdapter.getDefaultAdapter();        // get Bluetooth adapter
            BC.checkBTState();
        }
    }
    private class ConnectedThread extends Thread {
        private final InputStream mmInStream;

        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
            } catch (IOException e) {
            }
            mmInStream = tmpIn;
        }
        public void run() {
            byte[] buffer = new byte[256];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);        // Get number of bytes and message in "buffer"
                    h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                } catch (IOException e) {
                    break;
                }
            }
        }
    }
}
Tab Page Adapter:
Java:
package com.example.ibm.exoskeleton_2;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.io.IOException;

public class TabsPagerAdapter extends FragmentPagerAdapter {
    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }
    @override
    public Fragment getItem(int index) {
        switch (index) {
        case 1:
            return new MainPage();
        case 0:
            return new ExtraExercise();
        case 2:
            return new OnYourOwn();
        }
        return null;
    }

    @override
    public int getCount() {
        // get item count - equal to number of tabs
        return 3;
    }

}
Bluetooth Communication Class:
Java:
package com.example.ibm.exoskeleton_2;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.io_OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;

/**
* Created by IBM on 07-Apr-15.
*/
public class BluetoothCommunication extends Fragment {
    public static final String TAG = "bluetooth2";
    public ConnectedThread mConnectedThread;
    public BluetoothAdapter btAdapter = null;
    public BluetoothSocket btSocket = null;

    // SPP UUID service
    public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // MAC-address of Bluetooth module (you must edit this line)
    public static String address = "00:06:66:68:30:D6";
    public BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        if(Build.VERSION.SDK_INT >= 10){
            try {
                final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                return (BluetoothSocket) m.invoke(device, MY_UUID);
            } catch (Exception e) {
                Log.e(TAG, "Could not create Insecure RFComm Connection", e);
            }
        }
        return  device.createRfcommSocketToServiceRecord(MY_UUID);
    }
    @override
    public void onResume() {
        super.onResume();

        Log.d(TAG, "...onResume - try connect...");

        // Set up a pointer to the remote node using it's address.
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        // Two things are needed to make a connection:
        //   A MAC address, which we got above.
        //   A Service ID or UUID.  In this case we are using the
        //     UUID for SPP.

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
        }

        // Discovery is resource intensive.  Make sure it isn't going on
        // when you attempt to connect and pass your message.
        btAdapter.cancelDiscovery();

        // Establish the connection.  This will block until it connects.
        Log.d(TAG, "...Connecting...");
        try {
            btSocket.connect();
            Log.d(TAG, "....Connection ok...");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
            }
        }

        // Create a data stream so we can talk to server.
        Log.d(TAG, "...Create Socket...");

        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();
    }

    @override
    public void onPause() {
        super.onPause();

        Log.d(TAG, "...In onPause()...");

        try     {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
        }
    }

    public void checkBTState() {
        // Check for Bluetooth support and then check to make sure it is turned on
        // Emulator doesn't support Bluetooth and will return null
        if(btAdapter==null) {
            //errorExit("Fatal Error", "Bluetooth not support");

        } else {
            if (btAdapter.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    public void errorExit(String title, String message){
        Toast.makeText(getActivity(), title + " - " + message, Toast.LENGTH_LONG).show();
        getActivity().finish();
    }

    public class ConnectedThread extends Thread {
        public final InputStream mmInStream;
        public final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void write(String message) {
            Log.d(TAG, "...Data to send: " + message + "...");
            byte[] msgBuffer = message.getBytes();
            try {
                mmOutStream.write(msgBuffer);
            } catch (IOException e) {
                Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
            }
        }

    }
    public BluetoothAdapter getBtAdapter()
    {
        return btAdapter;
    }
    public BluetoothSocket getBtSocket ()
    {
        return btSocket;
    }
}
Main Activity:
Java:
package com.example.ibm.exoskeleton_2;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.support.v4.view.ViewPager;

import java.io.IOException;

public class MainActivity extends ActionBarActivity implements
        ActionBar.TabListener, android.support.v7.app.ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private android.support.v7.app.ActionBar actionBar;
    private String[] tabs = { "Extra", "Main", "Readings" };
    // Tab titles
    BluetoothCommunication BC = new BluetoothCommunication();
    BluetoothCommunication.ConnectedThread mConnectedThread;
    BluetoothAdapter btAdapter = BC.getBtAdapter();
    BluetoothSocket btSocket = BC.getBtSocket();

    @override
    protected void onCreate(Bundle savedInstanceState) {
        BC.btAdapter.enable();
        try {
            BC.btSocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getSupportActionBar();
       mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
       actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }
        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }


    @override
    public void onTabSelected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @override
    public void onTabUnselected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {

    }

    @override
    public void onTabReselected(android.support.v7.app.ActionBar.Tab tab, android.support.v4.app.FragmentTransaction fragmentTransaction) {

    }
}
Android Manefist:
Java:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="[URL]http://schemas.android.com/apk/res/android[/URL]"
    package="com.example.ibm.exoskeleton_2" >
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
   <application
        android:allowBackup="true"
        android:icon="@Mipmap/ic_launcher"
        android:label="@String/app_name"
        android:theme="@Style/AppTheme" >
        <activity
            android:name=".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>
 
Last edited by a moderator:
I did a small stupid modification to the code but which made it 50% work. What I did is that I copied everything inside the BluetoothCommunication class and paste it in every fragment. This way established a connection with the bluetooth module but there is a problem which is that I can't send data to the bluetooth. I kept trying but nothing worked. :'(
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones