IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Studio Java Discussion :

Bluetooth avec plusieurs fragments Android Studio


Sujet :

Android Studio Java

  1. #1
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2018
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Mars 2018
    Messages : 6
    Points : 4
    Points
    4
    Par défaut Bluetooth avec plusieurs fragments Android Studio
    Bonjour à tous,

    N'ayant pas de grandes connaissances en programmation Android, je viens vous sollicité pour un de mes problèmes. Je dois créer une application Android capable de transférer des données entre elle-même et une Raspberry. Comme j'ai besoin de faire plusieurs actions, j'ai décidé d'utiliser un navigation drawer avec les fragments. Pour la connexion à la Raspberry et l'ouverture de la connexion, le programme présent dans le fragment fonction très bien car la Raspberry m'informe que la communication est ouverte. Voici le programme:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    package com.gxabt.uliege.microspectro_v1.Controllers.Fragments;
     
    import android.Manifest;
    import android.app.Fragment;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.Build;
    import android.os.Bundle;
    import android.support.v4.content.LocalBroadcastManager;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.ListView;
     
    import com.gxabt.uliege.microspectro_v1.Models.BluetoothConnectionService;
    import com.gxabt.uliege.microspectro_v1.Models.DeviceListAdapter;
    import com.gxabt.uliege.microspectro_v1.R;
     
    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.Set;
    import java.util.UUID;
     
    public class ConnectionFragment extends Fragment implements AdapterView.OnItemClickListener {
        private static final String TAG = "ConnectionFragment";
        private static final UUID MY_UUID_INSECURE = UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");
     
        public ArrayList<BluetoothDevice> mBTDevices;
        public Set<BluetoothDevice> mDeviceBonded;
        public DeviceListAdapter mDeviceListAdapter;
     
        BluetoothConnectionService mBluetoothConnection;
        BluetoothAdapter mBluetoothAdapter;
        BluetoothDevice mBTDevice;
        ListView lvDevices;
        Button btnStartConnection;
        Button btnSearch;
        StringBuilder message;
     
        public static ConnectionFragment newInstance() {
            return (new ConnectionFragment());
        }
     
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_connection, container, false);
     
            mBTDevices = new ArrayList<>();
     
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
     
            mDeviceBonded = mBluetoothAdapter.getBondedDevices();
     
            lvDevices = (ListView) rootView.findViewById(R.id.list_devices);
     
            for (BluetoothDevice bt : mDeviceBonded)
            {
                mBTDevices.add(bt);
            }
     
            mDeviceListAdapter = new DeviceListAdapter(getActivity(), R.layout.device_adapteur_view, mBTDevices);
            lvDevices.setAdapter(mDeviceListAdapter);
     
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
            getActivity().registerReceiver(mBroadcastReceiverBound, filter);
            lvDevices.setOnItemClickListener(ConnectionFragment.this);
     
            btnStartConnection = (Button) rootView.findViewById(R.id.fragment_connect_btn_start);
            btnStartConnection.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view) {
                    startConnection();
                }
            });
     
            btnSearch = (Button) rootView.findViewById(R.id.fragment_connect_btn_search);
            btnSearch.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    Log.d(TAG, "btnDiscover: Looking for unpaired devices...");
     
                    if (mBluetoothAdapter.isDiscovering()) {
                        mBluetoothAdapter.cancelDiscovery();
                        Log.d(TAG, "btnDiscover: Canceling discovery.");
     
                        //Check BT permissions in manifest
                        checkBTPermissions();
     
                        mBluetoothAdapter.startDiscovery();
                        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                        getActivity().registerReceiver(mBroadcastReceiverDiscover, discoverDevicesIntent);
                    }
                    if (!mBluetoothAdapter.isDiscovering()) {
                        //Check BT permissions in manifest
                        checkBTPermissions();
     
                        mBluetoothAdapter.startDiscovery();
                        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                        getActivity().registerReceiver(mBroadcastReceiverDiscover, discoverDevicesIntent);
                    }
                }
            });
     
            message = new StringBuilder();
            LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mReceiver, new IntentFilter("incomingMessage"));
     
            return rootView;
        }
     
     
        public void startBTConnection(BluetoothDevice device, UUID uuid) {
            Log.d(TAG, "startBTConnection: Initializing RFCOM Bluetooth Connection");
     
            mBluetoothConnection.startClient(device, uuid);
        }
     
        //Remember the connection will fail and app will crash if you haven't paired first
        public void startConnection()
        {
            startBTConnection(mBTDevice, MY_UUID_INSECURE);
        }
     
        /*
            Discover new devices.
            This broadcast receiver is use for listening devices that are not yet paired.
         */
        private final BroadcastReceiver mBroadcastReceiverDiscover = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final String action = intent.getAction();
                Log.d(TAG, "onReciver: ACTION FOUND.");
     
                if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.d(TAG, "onReceive: " + device.getName() + " : " + device.getAddress());
     
                    int i = 0;
                    for (; i < mBTDevices.size(); i++) {
                        if (device.getAddress().equals(mBTDevices.get(i).getAddress())) {
                            break;
                        }
                    }
     
                    if (i == mBTDevices.size()) {
                        mBTDevices.add(device);
                    }
     
                    mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapteur_view, mBTDevices);
                    lvDevices.setAdapter(mDeviceListAdapter);
                }
            }
        };
     
        /*
            Bounding devices.
         */
        private final BroadcastReceiver mBroadcastReceiverBound = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final String action = intent.getAction();
     
                if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                    BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    // Case 1: bounded already
                    if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                        Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
     
                        mBTDevice = mDevice;
                    }
                    // Case 2: creating a bone
                    if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
                        Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
                    }
                    // Case 3: breaking a bond
                    if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                        Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
                    }
                }
            }
        };
     
        BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String text = intent.getStringExtra("theMessage");
     
                message.append(text + "\n");
            }
        };
     
        /*
            Check permissions method.
            This method is required for all devices running API23+.
            Android must programmatically check the permissions for Bluetooth.
            Putting the proper permissions in the manifest is not enough.
     
            NOTE: This will only execute on version >LOLLIPOP because it is not needed otherwise.
         */
        public void checkBTPermissions() {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                int permissionCheck = this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
                permissionCheck += this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
                if (permissionCheck != 0) {
                    this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
                }
            } else {
                Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
            }
        }
     
        /*
            Bounding device - item click
         */
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //First cancel discovery because its very memory intensive.
            mBluetoothAdapter.cancelDiscovery();
            Log.d(TAG, "onItemClick: You Clicked on a device.");
            String deviceName = mBTDevices.get(i).getName();
            String deviceAddress = mBTDevices.get(i).getAddress();
     
            Log.d(TAG, "onItemClick: " + deviceName);
            Log.d(TAG, "onItemClick: " + deviceAddress);
     
            //Create the bond
            //NOTE: Requires API 17+
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                Log.d(TAG, "Trying to pair with " + deviceName);
                mBTDevices.get(i).createBond();
     
                mBTDevice = mBTDevices.get(i);
                mBluetoothConnection = new BluetoothConnectionService(getActivity());
            }
        }
    }
    Mais lorsque je change de fragment et que j'appuie sur le bouton pour envoyer les informations, j'obtiens un message d'erreur. Voici le programme du fragment d'envoi:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    package com.gxabt.uliege.microspectro_v1.Controllers.Fragments;
     
    import android.app.Fragment;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
     
    import com.gxabt.uliege.microspectro_v1.Controllers.Activities.MainActivity;
    import com.gxabt.uliege.microspectro_v1.Models.BluetoothConnectionService;
    import com.gxabt.uliege.microspectro_v1.R;
     
    import java.nio.charset.Charset;
    import java.util.UUID;
     
    public class ReproductionFragment extends Fragment
    {
        private static final UUID MY_UUID_INSECURE = UUID.fromString("00001105-0000-1000-8000-00805F9B34FB");
     
        Button btnReprod;
        BluetoothConnectionService mBluetoothConnection;
        ConnectionFragment dev;
        MainActivity sendData;
     
        public static ReproductionFragment newInstance()
        {
            return (new ReproductionFragment());
        }
     
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            View rootView = inflater.inflate(R.layout.fragment_reproduction, container, false);
     
            btnReprod = (Button) rootView.findViewById(R.id.fragment_reprod_btn_reprod);
            //mBluetoothConnection.startClient(mBluetoothConnection.mmDevice, MY_UUID_INSECURE);
     
            btnReprod.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View view)
                {
                    String msg = "bp_reprod";
                    byte[] bytes = msg.getBytes(Charset.defaultCharset());
                    try
                    {
                        mBluetoothConnection.write(bytes);
                    }
                    catch (NullPointerException e)
                    {
                        e.printStackTrace();
                    }
                }
            });
     
            return rootView;
        }
    }
    Et voici les erreurs que je reçois:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    03-19 12:49:21.399 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err: java.lang.NullPointerException
    03-19 12:49:21.429 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at com.gxabt.uliege.microspectro_v1.Controllers.Fragments.ReproductionFragment$1.onClick(ReproductionFragment.java:49)
    03-19 12:49:21.429 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at android.view.View.performClick(View.java:4147)
    03-19 12:49:21.429 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at android.view.View$PerformClick.run(View.java:17161)
    03-19 12:49:21.429 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at android.os.Handler.handleCallback(Handler.java:615)
    03-19 12:49:21.439 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:92)
    03-19 12:49:21.439 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at android.os.Looper.loop(Looper.java:213)
    03-19 12:49:21.439 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:4786)
    03-19 12:49:21.439 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
    03-19 12:49:21.439 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at java.lang.reflect.Method.invoke(Method.java:511)
    03-19 12:49:21.439 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
    03-19 12:49:21.439 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
    03-19 12:49:21.439 26997-26997/com.gxabt.uliege.microspectro_v1 W/System.err:     at dalvik.system.NativeStart.main(Native Method)
    Pouvez-Vous m'aider avec ce problème ?

    Merci

  2. #2
    Membre éprouvé Avatar de Drowan
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2014
    Messages
    460
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 29
    Localisation : France, Isère (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Juin 2014
    Messages : 460
    Points : 1 014
    Points
    1 014
    Par défaut

    Dans ta classe ReproductionFragment, tu as un attribut mBluetoothConnection que tu n'initialise jamais. Il est donc null. Ainsi quand à la ligne 49 de cette callse tu fais mBluetoothConnection.write(bytes);, java ne connait pas la methode write sur l'objet null (normal), Donc il te donne cette erreur.
    "On sera toujours mieux installé assis en 1ère que debout en 2nde", un illustre inconnu


    Avant de poser une question vérifiez si elle n'a pas déjà une réponse dans les cours et tutoriels
    Si votre problème est pensez à marquer la conversation comme telle
    Si un message est utile, pertinent, et/ou vous êtes d'accord avec, pensez à à l'inverse s'il est inutile, faux ou que vous n'êtes pas d'accord, pensez à

  3. #3
    Candidat au Club
    Homme Profil pro
    Étudiant
    Inscrit en
    Mars 2018
    Messages
    6
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 26
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Électronique et micro-électronique

    Informations forums :
    Inscription : Mars 2018
    Messages : 6
    Points : 4
    Points
    4
    Par défaut
    Oui c'est vrai. Donc je dois refaire un truc du genre "mBluetoothConnection = new BluetoothConnectionService(getActivity)" ? Mais alors il faut aussi que je lui passe le nom du device et le uuid ?

Discussions similaires

  1. Réponses: 6
    Dernier message: 23/04/2019, 03h12
  2. [Débutante] Application Android codé avec JAVA sous Android Studio
    Par aurelie8013 dans le forum Android Studio
    Réponses: 8
    Dernier message: 05/10/2017, 11h16
  3. Connexion avec Google sur Android Studio
    Par backx3 dans le forum Android Studio
    Réponses: 4
    Dernier message: 04/04/2017, 10h02
  4. Réponses: 12
    Dernier message: 23/04/2009, 14h53
  5. Réponses: 1
    Dernier message: 27/06/2007, 16h01

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo