Partage
  • Partager sur Facebook
  • Partager sur Twitter

[Android] Récupérer une variable d'une autre class

    18 septembre 2017 à 20:29:34

    Bonjour,

    j'ai un petit soucis tout bête, je n'arrive pas à récupérer une variable d'une autre classe.
    Je m'explique :

    Dans ma première classe (MainActivity) : 

    Je créé une variable provenant d'un évènement setOnClickListener d'un spinner. En gros, l'utilisateur clique sur un des choix de spinner. Le spinner est agrémenté par une énumération. Chaque proposition du spinner donne une valeur. 

    Je la renvoie à l'aide de la fonction return. 

    Ensuite je clique sur un bouton "next page" qui m'emmène à la page suivante.

    Dans cette page suivante (classe NextPage) : 

    Je souhaite, dans un premier temps récupérer la variable de ma page précédente. Malheureusement je n'y arrive pas ^^ Voici le code : 

    MainActivity : 

    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.Spinner;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity {
    
        public static final String TAG = "MainActivity";
    
        //définition du button
        Button button1;
    
        //initialisation de la variable var
        public int var = 0;
        public int variable = 0;
    
        //création de l'objet Spinner
        Spinner spinner1;
    
        //pour ajouter des datas dans un spinner, on a besoin d'un "adapteur"
        ArrayAdapter<CharSequence> adapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
    
            //initialisation des objets Spinner
            spinner1 = (Spinner) findViewById(R.id.spinner1);
    
            //on set les valeurs des énumérations dans le  spinner grâce à ArrayAdapter
            spinner1.setAdapter(new ArrayAdapter<MyEnum1>(this, android.R.layout.simple_spinner_item, MyEnum1.values()));
    
            //création de l'évènement qui va gérer le spinner1
            spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    
                    var = ((MyEnum1) parent.getItemAtPosition(position)).getA();
                    
    
                }
    
                @Override
                public void onNothingSelected(AdapterView<?> parent) {
    
                }
            });
    
            //final byte varbyte = (byte)var;
    
    
            button1 = (Button) findViewById(R.id.button2);
    
            button1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    Toast.makeText(MainActivity.this, "var = "+var, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(MainActivity.this, NextPage.class);
                    startActivity(intent);
    
                }
            });
    
        }
    
        public int getvar(){
            variable = var;
            return variable;
        }
    }

    NextPage : 

    public class NextPage extends MainActivity implements AdapterView.OnItemClickListener {
        int vava = MainActivity.getvar(variable); 
    }

    Malheureusement mon "getvar" n'est pas lisible dans la classe "NextPage".

    J'imagine que le problème est tout bête mais je n'arrive pas à le résoudre.

    Merci d'avance pour votre aide! 

    Cyril 

    -
    Edité par CyrilBaltz 18 septembre 2017 à 20:30:19

    • Partager sur Facebook
    • Partager sur Twitter
      18 septembre 2017 à 21:59:29

      Salut !

      Pour passer une variable d'une activité à une autre, tu dois passer la variable en utilisant la méthode putExtra sur ton intent. Si tu veux j'en parle dans cette vidéo : https://www.youtube.com/watch?v=_5osl5e_hE8

      Concernant ta classe NextPage, qui est une activité à part entière, tu dois la faire hériter de AppCompatActivity et non de MainActivity et tu dois implémenter les méthodes nécessaires à une activité, et notamment la méthode onCreate. Ta classe NextPage est une activité au même titre que MainActivity.

      • Partager sur Facebook
      • Partager sur Twitter
        18 septembre 2017 à 23:25:37

        Salut!

        Super ta vidéo, j'ai bien compris comment ça marche! 

        Effectivement, je n'ai pas développé l'activité NextPage pour ne pas embrouillé tous le monde car le programme est assez "lourd". Mais effectivement, petite erreur de ma part pour le AppCompatActivity! Il n'empêche que mon application plante lorsque je clique sur le bouton pour passer à la page suivante. Si jamais tu as l'occasion de regarder, voici l'application : 

        Le but est de créer une variable avec un spinner (incrémenté via une énumération) et de gérer le bluetooth sur la page suivante (activation, discover device, appareillage et envoye de la variable) : 

        MainActivity : 

        import android.content.Intent;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.ArrayAdapter;
        import android.widget.Button;
        import android.widget.Spinner;
        
        public class MainActivity extends AppCompatActivity {
        
            public static final String TAG = "MainActivity";
        
            //définition du button
            Button button1;
        
            //initialisation de la variable var
            public int var = 0;
            public int variable = 0;
        
            //création de l'objet Spinner
            Spinner spinner1;
        
            //pour ajouter des datas dans un spinner, on a besoin d'un "adapteur"
            ArrayAdapter<CharSequence> adapter;
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
        
        
                //initialisation des objets Spinner
                spinner1 = (Spinner) findViewById(R.id.spinner1);
        
                //on set les valeurs des énumérations dans le  spinner grâce à ArrayAdapter
                spinner1.setAdapter(new ArrayAdapter<MyEnum1>(this, android.R.layout.simple_spinner_item, MyEnum1.values()));
        
                //création de l'évènement qui va gérer le spinner1
                spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        
                        var = ((MyEnum1) parent.getItemAtPosition(position)).getA();
                    }
        
                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
        
                    }
                });
        
                button1 = (Button) findViewById(R.id.button2);
        
                button1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
        
                        //Toast.makeText(MainActivity.this, "var = "+var, Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(MainActivity.this, NextPage.class);
                        intent.putExtra("variable", var);
                        startActivity(intent);
                    }
                });
            }
        }

        xml activity_main : 

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="20dp">
        
        
        
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center"
                android:text="Je suis?"
                android:textSize="25sp"
                android:textStyle="bold" />
        
        
            <Spinner
                android:id="@+id/spinner1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="sélectionner genre"/>
        
        
            <Space
                android:layout_width="match_parent"
                android:layout_height="20dp"></Space>
        
            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1">
        
                <Button
                    android:id="@+id/button2"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:padding="20dp"
                    android:text="next page"
                    android:textSize="18sp" ></Button>
        
            </FrameLayout>
        
        
        </LinearLayout>

        Enumération, "MyEnum1" : 

        public enum MyEnum1 {
        
            Boy("homme",  1),
            Girl("femme", 0);
        
            private final String label;
        
            public final int a;
        
            private MyEnum1(String label, int a){
                this.a = a;
                this.label = label;
            }
        
            @Override
            public String toString(){
                return label;
            }
        
            public int getA(){
                return a;
            }
        
        }
        

        NextPage :

        import android.Manifest;
        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.v7.app.AppCompatActivity;
        import android.util.Log;
        import android.view.View;
        import android.widget.AdapterView;
        import android.widget.Button;
        import android.widget.ListView;
        
        import java.util.ArrayList;
        import java.util.UUID;
        /**
         * Created by Cyril on 27/04/2017.
         */
        
        public class NextPage extends AppCompatActivity implements AdapterView.OnItemClickListener {
            private static final String TAG = "NextPage";
        
            MainActivity Ma;
        
            BluetoothAdapter mBluetoothAdapter;
            Button btnEnableDisable_Discoverable;
        
            BluetoothConnectionService mBluetoothConnection;
        
            Button btnStartConnection;
            Button btnSend;
        
            private static final UUID MY_UUID_INSECURE =
                    UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
        
            BluetoothDevice mBTDevice;
        
            public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
        
            public DeviceListAdapter mDeviceListAdapter;
        
            ListView lvNewDevices;
        
        
            // Create a BroadcastReceiver for ACTION_FOUND
            private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    // When discovery finds a device
                    if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
                        final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
        
                        switch(state){
                            case BluetoothAdapter.STATE_OFF:
                                Log.d(TAG, "onReceive: STATE OFF");
                                break;
                            case BluetoothAdapter.STATE_TURNING_OFF:
                                Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
                                break;
                            case BluetoothAdapter.STATE_ON:
                                Log.d(TAG, "mBroadcastReceiver1: STATE ON");
                                break;
                            case BluetoothAdapter.STATE_TURNING_ON:
                                Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
                                break;
                        }
                    }
                }
            };
        
            /**
             * Broadcast Receiver for changes made to bluetooth states such as:
             * 1) Discoverability mode on/off or expire.
             */
            private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
        
                @Override
                public void onReceive(Context context, Intent intent) {
                    final String action = intent.getAction();
        
                    if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
        
                        int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
        
                        switch (mode) {
                            //Device is in Discoverable Mode
                            case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
                                Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
                                break;
                            //Device not in discoverable mode
                            case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
                                Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
                                break;
                            case BluetoothAdapter.SCAN_MODE_NONE:
                                Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
                                break;
                            case BluetoothAdapter.STATE_CONNECTING:
                                Log.d(TAG, "mBroadcastReceiver2: Connecting....");
                                break;
                            case BluetoothAdapter.STATE_CONNECTED:
                                Log.d(TAG, "mBroadcastReceiver2: Connected.");
                                break;
                        }
        
                    }
                }
            };
        
        
            /**
             * Broadcast Receiver for listing devices that are not yet paired
             * -Executed by btnDiscover() method.
             */
            private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    final String action = intent.getAction();
                    Log.d(TAG, "onReceive: ACTION FOUND.");
        
                    if (action.equals(BluetoothDevice.ACTION_FOUND)){
                        BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
                        mBTDevices.add(device);
                        Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
                        mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
                        lvNewDevices.setAdapter(mDeviceListAdapter);
                    }
                }
            };
        
            /**
             * Broadcast Receiver that detects bond state changes (Pairing status changes)
             */
            private final BroadcastReceiver mBroadcastReceiver4 = 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);
                        //3 cases:
                        //case1: bonded already
                        if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
                            Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
                            //inside BroadcastReceiver4
                            mBTDevice = mDevice;
                        }
                        //case2: creating a bone
                        if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
                            Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
                        }
                        //case3: breaking a bond
                        if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                            Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
                        }
                    }
                }
            };
        
        
        
            @Override
            protected void onDestroy() {
                Log.d(TAG, "onDestroy: called.");
                super.onDestroy();
                unregisterReceiver(mBroadcastReceiver1);
                unregisterReceiver(mBroadcastReceiver2);
                unregisterReceiver(mBroadcastReceiver3);
                unregisterReceiver(mBroadcastReceiver4);
            }
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.page_bluetooth);
        
                Intent intent1 = getIntent();
                int varbyte = intent1.getIntExtra("variable", 0);
                final byte transvar = (byte)varbyte;
        
                Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
                btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
                lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
                mBTDevices = new ArrayList<>();
        
                btnStartConnection = (Button) findViewById(R.id.btnStartConnection);
                btnSend = (Button) findViewById(R.id.buttonSend);
        
                //Broadcasts when bond state changes (ie:pairing)
                IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
                registerReceiver(mBroadcastReceiver4, filter);
        
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        
                lvNewDevices.setOnItemClickListener(NextPage.this);
        
        
                btnONOFF.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.d(TAG, "onClick: enabling/disabling bluetooth.");
                        enableDisableBT();
                    }
                });
        
                btnStartConnection.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startConnection();
                    }
                });
        
                btnSend.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        byte[] bytes = new byte[]{transvar};
                        mBluetoothConnection.write(bytes);
                    }
                });
        
            }
        
            //create method for starting connection
        //***remember the conncction will fail and app will crash if you haven't paired first
            public void startConnection(){
                startBTConnection(mBTDevice,MY_UUID_INSECURE);
            }
        
            /**
             * starting chat service method
             */
            public void startBTConnection(BluetoothDevice device, UUID uuid){
                Log.d(TAG, "startBTConnection: Initializing RFCOM Bluetooth Connection.");
        
                mBluetoothConnection.startClient(device,uuid);
            }
        
        
        
            public void enableDisableBT(){
                if(mBluetoothAdapter == null){
                    Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
                }
                if(!mBluetoothAdapter.isEnabled()){
                    Log.d(TAG, "enableDisableBT: enabling BT.");
                    Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivity(enableBTIntent);
        
                    IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(mBroadcastReceiver1, BTIntent);
                }
                if(mBluetoothAdapter.isEnabled()){
                    Log.d(TAG, "enableDisableBT: disabling BT.");
                    mBluetoothAdapter.disable();
        
                    IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
                    registerReceiver(mBroadcastReceiver1, BTIntent);
                }
        
            }
        
        
            public void btnEnableDisable_Discoverable(View view) {
                Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
        
                Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
                startActivity(discoverableIntent);
        
                IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
                registerReceiver(mBroadcastReceiver2,intentFilter);
        
            }
        
            public void btnDiscover(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);
                    registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
                }
                if(!mBluetoothAdapter.isDiscovering()){
        
                    //check BT permissions in manifest
                    checkBTPermissions();
        
                    mBluetoothAdapter.startDiscovery();
                    IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
                    registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
                }
            }
        
            /**
             * 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 versions > LOLLIPOP because it is not needed otherwise.
             */
            private void checkBTPermissions() {
                if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
                    int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
                    permissionCheck += this.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.");
                }
            }
        
        
        
            @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 = " + deviceName);
                Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
        
                //create the bond.
                //NOTE: Requires API 17+? I think this is JellyBean
                if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
                    Log.d(TAG, "Trying to pair with " + deviceName);
                    mBTDevices.get(i).createBond();
        
                    mBTDevice = mBTDevices.get(i);
                    mBluetoothConnection = new BluetoothConnectionService(NextPage.this);
                }
            }
        }

        xml associé "page_bluetooth" : 

        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        
        
        
            <Button
                android:text="ON/OFF"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_alignParentRight="true"
                android:id="@+id/btnONOFF"/>
        
            <Button
                android:text="Enable Discoverable"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnDiscoverable_on_off"
                android:onClick="btnEnableDisable_Discoverable"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"/>
        
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btnFindUnpairedDevices"
                android:text="Discover"
                android:onClick="btnDiscover"/>
        
            <Button
                android:layout_marginTop="10dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/btnFindUnpairedDevices"
                android:id="@+id/btnStartConnection"
                android:text="Start Connection"/>
        
            <ListView
                android:layout_marginTop="15dp"
                android:layout_below="@id/btnStartConnection"
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:id="@+id/lvNewDevices"/>
        
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Envoyer info"
                android:id="@+id/buttonSend"
                android:layout_below="@+id/lvNewDevices"/>
        
        
        
        </RelativeLayout>

        DeviceListAdapter : 

        import android.bluetooth.BluetoothDevice;
        import android.content.Context;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.ArrayAdapter;
        import android.widget.TextView;
        
        import java.util.ArrayList;
        
        
        public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {
        
            private LayoutInflater mLayoutInflater;
            private ArrayList<BluetoothDevice> mDevices;
            private int  mViewResourceId;
        
            public DeviceListAdapter(Context context, int tvResourceId, ArrayList<BluetoothDevice> devices){
                super(context, tvResourceId,devices);
                this.mDevices = devices;
                mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                mViewResourceId = tvResourceId;
            }
        
            public View getView(int position, View convertView, ViewGroup parent) {
                convertView = mLayoutInflater.inflate(mViewResourceId, null);
        
                BluetoothDevice device = mDevices.get(position);
        
                if (device != null) {
                    TextView deviceName = (TextView) convertView.findViewById(R.id.tvDeviceName);
                    TextView deviceAdress = (TextView) convertView.findViewById(R.id.tvDeviceAddress);
        
                    if (deviceName != null) {
                        deviceName.setText(device.getName());
                    }
                    if (deviceAdress != null) {
                        deviceAdress.setText(device.getAddress());
                    }
                }
        
                return convertView;
            }
        
        }

        xml associé device_adaptater_view : 

        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" android:layout_width="match_parent"
            android:layout_height="match_parent">
        
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/tvDeviceName"
                android:textSize="15sp"/>
        
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/tvDeviceAddress"
                android:textSize="15sp"/>
        
        </LinearLayout>

        et la classe qui gère les différents thread pour le bluetooth "BluetoothConnectionService" : 

        import android.app.ProgressDialog;
        import android.bluetooth.BluetoothAdapter;
        import android.bluetooth.BluetoothDevice;
        import android.bluetooth.BluetoothServerSocket;
        import android.bluetooth.BluetoothSocket;
        import android.content.Context;
        import android.util.Log;
        
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.OutputStream;
        import java.nio.charset.Charset;
        import java.util.UUID;
        
        /**
         * Created by User on 12/21/2016.
         */
        
        public class BluetoothConnectionService {
            private static final String TAG = "BluetoothConnectionServ";
        
            private static final String appName = "MYAPP";
        
            private static final UUID MY_UUID_INSECURE =
                    UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
        
            private final BluetoothAdapter mBluetoothAdapter;
            Context mContext;
        
            private AcceptThread mInsecureAcceptThread;
        
            private ConnectThread mConnectThread;
            private BluetoothDevice mmDevice;
            private UUID deviceUUID;
            ProgressDialog mProgressDialog;
        
            private ConnectedThread mConnectedThread;
        
            public BluetoothConnectionService(Context context) {
                mContext = context;
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                start();
            }
        
        
            /**
             * This thread runs while listening for incoming connections. It behaves
             * like a server-side client. It runs until a connection is accepted
             * (or until cancelled).
             */
            private class AcceptThread extends Thread {
        
                // The local server socket
                private final BluetoothServerSocket mmServerSocket;
        
                public AcceptThread(){
                    BluetoothServerSocket tmp = null;
        
                    // Create a new listening server socket
                    try{
                        tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);
        
                        Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
                    }catch (IOException e){
                        Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
                    }
        
                    mmServerSocket = tmp;
                }
        
                public void run(){
                    Log.d(TAG, "run: AcceptThread Running.");
        
                    BluetoothSocket socket = null;
        
                    try{
                        // This is a blocking call and will only return on a
                        // successful connection or an exception
                        Log.d(TAG, "run: RFCOM server socket start.....");
        
                        socket = mmServerSocket.accept();
        
                        Log.d(TAG, "run: RFCOM server socket accepted connection.");
        
                    }catch (IOException e){
                        Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
                    }
        
                    //talk about this is in the 3rd
                    if(socket != null){
                        connected(socket,mmDevice);
                    }
        
                    Log.i(TAG, "END mAcceptThread ");
                }
        
                public void cancel() {
                    Log.d(TAG, "cancel: Canceling AcceptThread.");
                    try {
                        mmServerSocket.close();
                    } catch (IOException e) {
                        Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
                    }
                }
        
            }
        
            /**
             * This thread runs while attempting to make an outgoing connection
             * with a device. It runs straight through; the connection either
             * succeeds or fails.
             */
            private class ConnectThread extends Thread {
                private BluetoothSocket mmSocket;
        
                public ConnectThread(BluetoothDevice device, UUID uuid) {
                    Log.d(TAG, "ConnectThread: started.");
                    mmDevice = device;
                    deviceUUID = uuid;
                }
        
                public void run(){
                    BluetoothSocket tmp = null;
                    Log.i(TAG, "RUN mConnectThread ");
        
                    // Get a BluetoothSocket for a connection with the
                    // given BluetoothDevice
                    try {
                        Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
                                +MY_UUID_INSECURE );
                        tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
                    } catch (IOException e) {
                        Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
                    }
        
                    mmSocket = tmp;
        
                    // Always cancel discovery because it will slow down a connection
                    mBluetoothAdapter.cancelDiscovery();
        
                    // Make a connection to the BluetoothSocket
        
                    try {
                        // This is a blocking call and will only return on a
                        // successful connection or an exception
                        mmSocket.connect();
        
                        Log.d(TAG, "run: ConnectThread connected.");
                    } catch (IOException e) {
                        // Close the socket
                        try {
                            mmSocket.close();
                            Log.d(TAG, "run: Closed Socket.");
                        } catch (IOException e1) {
                            Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
                        }
                        Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
                    }
        
                    connected(mmSocket,mmDevice);
                }
                public void cancel() {
                    try {
                        Log.d(TAG, "cancel: Closing Client Socket.");
                        mmSocket.close();
                    } catch (IOException e) {
                        Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
                    }
                }
            }
        
        
        
            /**
             * Start the chat service. Specifically start AcceptThread to begin a
             * session in listening (server) mode. Called by the Activity onResume()
             */
            public synchronized void start() {
                Log.d(TAG, "start");
        
                // Cancel any thread attempting to make a connection
                if (mConnectThread != null) {
                    mConnectThread.cancel();
                    mConnectThread = null;
                }
                if (mInsecureAcceptThread == null) {
                    mInsecureAcceptThread = new AcceptThread();
                    mInsecureAcceptThread.start();
                }
            }
        
            /**
             AcceptThread starts and sits waiting for a connection.
             Then ConnectThread starts and attempts to make a connection with the other devices AcceptThread.
             **/
        
            public void startClient(BluetoothDevice device,UUID uuid){
                Log.d(TAG, "startClient: Started.");
        
                //initprogress dialog
                mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
                        ,"Please Wait...",true);
        
                mConnectThread = new ConnectThread(device, uuid);
                mConnectThread.start();
            }
        
            /**
             Finally the ConnectedThread which is responsible for maintaining the BTConnection, Sending the data, and
             receiving incoming data through input/output streams respectively.
             **/
            private class ConnectedThread extends Thread {
                private final BluetoothSocket mmSocket;
                private final InputStream mmInStream;
                private final OutputStream mmOutStream;
        
                public ConnectedThread(BluetoothSocket socket) {
                    Log.d(TAG, "ConnectedThread: Starting.");
        
                    mmSocket = socket;
                    InputStream tmpIn = null;
                    OutputStream tmpOut = null;
        
                    //dismiss the progressdialog when connection is established
                    try{
                        mProgressDialog.dismiss();
                    }catch (NullPointerException e){
                        e.printStackTrace();
                    }
        
        
                    try {
                        tmpIn = mmSocket.getInputStream();
                        tmpOut = mmSocket.getOutputStream();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
        
                    mmInStream = tmpIn;
                    mmOutStream = tmpOut;
                }
        
                public void run(){
                    byte[] buffer = new byte[1024];  // buffer store for the stream
        
                    int bytes; // bytes returned from read()
        
                    // Keep listening to the InputStream until an exception occurs
                    while (true) {
                        // Read from the InputStream
                        try {
                            bytes = mmInStream.read(buffer);
                            String incomingMessage = new String(buffer, 0, bytes);
                            Log.d(TAG, "InputStream: " + incomingMessage);
                        } catch (IOException e) {
                            Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
                            break;
                        }
                    }
                }
        
                //Call this from the main activity to send data to the remote device
                public void write(byte[] bytes) {
                    Log.d(TAG, "write: Writing to outputstream: " + bytes);
                    try {
                        mmOutStream.write(bytes);
                    } catch (IOException e) {
                        Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
                    }
                }
        
                /* Call this from the main activity to shutdown the connection */
                public void cancel() {
                    try {
                        mmSocket.close();
                    } catch (IOException e) { }
                }
            }
        
            private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
                Log.d(TAG, "connected: Starting.");
        
                // Start the thread to manage the connection and perform transmissions
                mConnectedThread = new ConnectedThread(mmSocket);
                mConnectedThread.start();
            }
        
            /**
             * Write to the ConnectedThread in an unsynchronized manner
             *
             * @param out The bytes to write
             * @see ConnectedThread#write(byte[])
             */
            public void write(byte[] out) {
                // Create temporary object
                ConnectedThread r;
        
                // Synchronize a copy of the ConnectedThread
                Log.d(TAG, "write: Write Called.");
                //perform the write
                mConnectedThread.write(out);
            }
        
        }

        pour finir le manifest : 

        <?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.pandaenterprise.cyril.testbluetoothv3">
        
            <uses-feature android:name="android.hardware.bluetooth"/>
            <uses-permission android:name="android.permission.BLUETOOTH"/>
            <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
            <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
            <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
            <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>
        
            <application
                android:allowBackup="true"
                android:icon="@mipmap/ic_launcher"
                android:label="@string/app_name"
                android:roundIcon="@mipmap/ic_launcher_round"
                android:supportsRtl="true"
                android:theme="@style/AppTheme">
                <activity android:name=".MainActivity">
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />
        
                        <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
                </activity>
            </application>
        
        </manifest>

        Merci d'avance! Bonne lecture!







        • Partager sur Facebook
        • Partager sur Twitter
          19 septembre 2017 à 8:39:47

          Salut,

          Personne n'a envie de lire autant de code... Si ton application plante, elle produit une stacktrace dans le logcat. Poste là ici qu'on regarde.

          • Partager sur Facebook
          • Partager sur Twitter
            19 septembre 2017 à 12:15:00

            Oui effectivement c'est un peu la galère de lire ça comme ça... 

            Du coup la stracktrace, ça me donne ça une fois que je clique sur le bouton nextpage pour aller à l'ativity suivante : 

            12:10:28.782 3839-3839/com.pandaenterprise.cyril.testbluetoothv3 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                                     Process: com.pandaenterprise.cyril.testbluetoothv3, PID: 3839
                                                                                                     android.content.ActivityNotFoundException: Unable to find explicit activity class {com.pandaenterprise.cyril.testbluetoothv3/com.pandaenterprise.cyril.testbluetoothv3.NextPage}; have you declared this activity in your AndroidManifest.xml?
                                                                                                         at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1805)
                                                                                                         at android.app.Instrumentation.execStartActivity(Instrumentation.java:1523)
                                                                                                         at android.app.Activity.startActivityForResult(Activity.java:4225)
                                                                                                         at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
                                                                                                         at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
                                                                                                         at android.app.Activity.startActivityForResult(Activity.java:4183)
                                                                                                         at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
                                                                                                         at android.app.Activity.startActivity(Activity.java:4522)
                                                                                                         at android.app.Activity.startActivity(Activity.java:4490)
                                                                                                         at com.pandaenterprise.cyril.testbluetoothv3.MainActivity$2.onClick(MainActivity.java:64)
                                                                                                         at android.view.View.performClick(View.java:5637)
                                                                                                         at android.view.View$PerformClick.run(View.java:22429)
                                                                                                         at android.os.Handler.handleCallback(Handler.java:751)
                                                                                                         at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                                                         at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
            

            Edit : J'ai trouvé mon erreur... Je n'avais pas déclaré "NextPage" dans mon manifest tout bêtement...

            Cependant, j'arrive à une nouvelle erreur générée par la page NextPage : 

            - en cliquant sur mon On/Off je peux activer le Bluetooth

            - En cliquant sur : Enable Discoverable, on peut me voir

            - En cliquant sur Discover je peux voir les devices dans mon array-list

            En cliquant sur "Start connection" mon app plante. Du coup j'ai un nouveau copié/collé de ma stacktrace au moment où l'app plante : 

            02-16 21:27:05.528 28622-28622/com.pandaenterprise.cyril.testbluetoothv3 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                                       java.lang.NullPointerException
                                                                                                           at com.pandaenterprise.cyril.testbluetoothv3.NextPage.startBTConnection(NextPage.java:243)
                                                                                                           at com.pandaenterprise.cyril.testbluetoothv3.NextPage.startConnection(NextPage.java:234)
                                                                                                           at com.pandaenterprise.cyril.testbluetoothv3.NextPage$6.onClick(NextPage.java:217)
                                                                                                           at android.view.View.performClick(View.java:4275)
                                                                                                           at android.view.View$PerformClick.run(View.java:17437)
                                                                                                           at android.os.Handler.handleCallback(Handler.java:615)
                                                                                                           at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                                           at android.os.Looper.loop(Looper.java:177)
                                                                                                           at android.app.ActivityThread.main(ActivityThread.java:4947)
                                                                                                           at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                                           at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
                                                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
                                                                                                           at dalvik.system.NativeStart.main(Native Method)

            Merci d'avance! 


            -
            Edité par CyrilBaltz 19 septembre 2017 à 12:40:49

            • Partager sur Facebook
            • Partager sur Twitter

            [Android] Récupérer une variable d'une autre class

            × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
            × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
            • Editeur
            • Markdown