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 Discussion :

erreur lorsque d'appel une méthode de class à un autre


Sujet :

Android

  1. #1
    Candidat au Club
    Inscrit en
    Avril 2013
    Messages
    3
    Détails du profil
    Informations forums :
    Inscription : Avril 2013
    Messages : 3
    Points : 3
    Points
    3
    Par défaut erreur lorsque d'appel une méthode de class à un autre
    bonjour,

    j'ai un problème d'une méthode write de class bluetooth lorsque j'ai l'appeler dans un autre class
    lorsque j'appuie sur le button elle m'affiche cette erreur
    at dalvik.system.NativeStart.main(Native Method)
    voila le code des deux class aidez moi SVP et merci d'avance
    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
     
    public class Touch extends Activity implements OnClickListener {
     
        Button button;
        bluetooth bt;
     
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.touch);
                    button =((Button)this.findViewById(R.id.button2));
                       button.setOnClickListener(this);
     
    	}
     
    	@Override
    	public void onClick(View arg0) {
     
               bt.write("mon message");    
     
     
    	}
    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
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
     
     
    public class bluetooth extends Activity implements OnItemClickListener, OnClickListener {
        int conx=0;
        String msg="";
        public ConnectThread mConnectThread=null;
        public ConnectedThread mConnectedThread=null;
    	ArrayAdapter<String> listAdapter;
    	ListView listView;
    	BluetoothAdapter btAdapter;
    	Set<BluetoothDevice> devicesArray;
    	ArrayList<String> pairedDevices;
    	ArrayList<BluetoothDevice> devices;
        public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    	protected static final int SUCCESS_CONNECT = 0;
    	protected static final int MESSAGE_READ = 1;
    	public static final int Touchpad_begin = 10;
     
    	IntentFilter filter;
    	Button button;
    	BroadcastReceiver receiver;
    	String tag = "debugging";
    	Souris_classique souris;
    	 public  InputStream mmInStream=null;
    	    public  OutputStream mmOutStream=null;
    	    public  BluetoothSocket mmSocket=null; 	 
    	Handler mHandler = new Handler(){
    		@Override
    		public void handleMessage(Message msg) {
    			// TODO Auto-generated method stub
    			Log.i(tag, "in handler");
    			super.handleMessage(msg);
    			switch(msg.what){
    			case SUCCESS_CONNECT:
    				// DO something
    				 mConnectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
    				conx=1;
    				Toast.makeText(getApplicationContext(), "CONNECT", 0).show();
     
     
    				String s = "successfully connected";
     
    				Log.i(tag, "connected");
     
    				break;
    			case MESSAGE_READ:
    				byte[] readBuf = (byte[])msg.obj;
    				String string = new String(readBuf);
    				Toast.makeText(getApplicationContext(), string, 0).show();
    				break;
    			}
    		}
    	};
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.bluetooth);
     
            init();
            if(btAdapter==null){
            	Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
            	finish();
            }
            else{
            	if(!btAdapter.isEnabled()){
            		turnOnBT();
            	}
     
            	getPairedDevices();
            	startDiscovery();
            }
     
     
        }
     
    	public void startDiscovery() {
    		// TODO Auto-generated method stub
    		btAdapter.cancelDiscovery();
    		btAdapter.startDiscovery();
     
    	}
    	public void turnOnBT() {
    		// TODO Auto-generated method stub
    		Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    		startActivityForResult(intent, 1);
    	}
    	public void getPairedDevices() {
    		// TODO Auto-generated method stub
    		devicesArray = btAdapter.getBondedDevices();
    		if(devicesArray.size()>0){
    			for(BluetoothDevice device:devicesArray){
    				pairedDevices.add(device.getName());
     
    			}
    		}
    	}
    	public void init() {
    		// TODO Auto-generated method stub
    		listView=(ListView)findViewById(R.id.listView);
    		listView.setOnItemClickListener(this);
    		button = ((Button)this.findViewById(R.id.next));
            button.setOnClickListener(this);
    		listAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    		listView.setAdapter(listAdapter);
    		btAdapter = BluetoothAdapter.getDefaultAdapter();
    		pairedDevices = new ArrayList<String>();
    		filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    		devices = new ArrayList<BluetoothDevice>();
    		receiver = new BroadcastReceiver(){
    			@Override
    			public void onReceive(Context context, Intent intent) {
    				// TODO Auto-generated method stub
    				String action = intent.getAction();
     
    				if(BluetoothDevice.ACTION_FOUND.equals(action)){
    					BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    					devices.add(device);
    					String s = "";
    					for(int a = 0; a < pairedDevices.size(); a++){
    						if(device.getName().equals(pairedDevices.get(a))){
    							//append 
    							s = "(Paired)";
    							break;
    						}
    					}
     
    					listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
    				}
     
    				else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
    					// run some code
    				}
    				else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
    					// run some code
     
     
     
    				}
    				else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
    					if(btAdapter.getState() == btAdapter.STATE_OFF){
    						turnOnBT();
    					}
    				}
     
    			}
    		};
     
    		registerReceiver(receiver, filter);
    		 filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    		registerReceiver(receiver, filter);
    		 filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    		registerReceiver(receiver, filter);
    		 filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    		registerReceiver(receiver, filter);
    	}
    	public void write(byte[] se) {
    		ConnectedThread r;
    		synchronized (this)
    		{
    			r=mConnectedThread;
    		}
    		r.write(se);
     
    	}
     
    	@Override
    	public void onPause() {
    		// TODO Auto-generated method stub
    		super.onPause();
    		unregisterReceiver(receiver);
    	}
     
    		@Override
    		public void onActivityResult(int requestCode, int resultCode, Intent data) {
    			// TODO Auto-generated method stub
    			super.onActivityResult(requestCode, resultCode, data);
    			if(resultCode == RESULT_CANCELED){
    				Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
    				finish();
     
    			}
     
    		}
     
    		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
    				long arg3) {
    			// TODO Auto-generated method stub
     
    			if(btAdapter.isDiscovering()){
    				btAdapter.cancelDiscovery();
    			}
    			if(listAdapter.getItem(arg2).contains("Paired")){
     
    				BluetoothDevice selectedDevice = devices.get(arg2);
    				mConnectThread = new ConnectThread(selectedDevice);
    				mConnectThread.start();
    				Log.i(tag, "in click listener");
    			}
    			else{
    				Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
    			}
     
    		}
     
    		public class ConnectThread extends Thread {
     
    			private final BluetoothSocket mmSocket;
    		    private final BluetoothDevice mmDevice;
     
    		    public ConnectThread(BluetoothDevice device) {
    		        // Use a temporary object that is later assigned to mmSocket,
    		        // because mmSocket is final
    		        BluetoothSocket tmp = null;
    		        mmDevice = device;
    		        Log.i(tag, "construct");
    		        // Get a BluetoothSocket to connect with the given BluetoothDevice
    		        try {
    		            // MY_UUID is the app's UUID string, also used by the server code
    		            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
    		        } catch (IOException e) { 
    		        	Log.i(tag, "get socket failed");
     
    		        }
    		        mmSocket = tmp;
    		    }
     
    		    public void run() {
    		        // Cancel discovery because it will slow down the connection
    		        btAdapter.cancelDiscovery();
    		        Log.i(tag, "connect - run");
    		        try {
    		            // Connect the device through the socket. This will block
    		            // until it succeeds or throws an exception
    		            mmSocket.connect();
     
     
    		        } catch (IOException connectException) {	Log.i(tag, "connect failed");
    		            // Unable to connect; close the socket and get out
    		            try {
    		                mmSocket.close();
    		            } catch (IOException closeException) { }
     
     
    		            return;
    		        }
     
    		        // Do work to manage the connection (in a separate thread)
     
    		        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    		    }
     
     
    			/** Will cancel an in-progress connection, and close the socket */
    		    public void cancel() {
    		        try {
    		            mmSocket.close();
    		        } catch (IOException e) { }
    		    }
    		}
     
    		public  class ConnectedThread extends Thread {
     
     
    // Interface de gestion d'une liaison BT RFCOMM
     
    		    public ConnectedThread(BluetoothSocket socket) {
    		        mmSocket = 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 run() {
    		        byte[] buffer;  // 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
    		            	buffer = new byte[1024];
    		                bytes = mmInStream.read(buffer);
    		                // Send the obtained bytes to the UI activity
    		                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
    		                        .sendToTarget();
     
    		            } catch (IOException e) {
    		                break;
    		            }
    		        }
    		    }
     
    		    /* Call this from the main activity to send data to the remote device */
    		    public void write(byte[] bytes) {
    		        try {
    		            mmOutStream.write(bytes);
    		           mmOutStream.flush();
     
    		        } catch (IOException e) { }
    		    }
     
    		    /* Call this from the main activity to shutdown the connection */
    		    public void cancel() {
    		        try {
    		            mmSocket.close();
    		        } catch (IOException e) { }
    		    }
    		}
     
     
    		@Override
    		public void onClick(View v) {
    			if(conx==1)
    			{
    			 Intent intent = new Intent(this,ChoixView.class);
    			 this.startActivityForResult(intent,1000);
     
    			}
    			else
    			{Toast.makeText(getApplicationContext(), "Please connect to device", 0).show();}
     
    		}
     
     
     
     
    }

  2. #2
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    "at dalvik.system.NativeStart.main(Native Method)" n'est pas une erreur mais l'endroit ou l'erreur s'est produite.
    Il nous faudrait l'ensemble de l'erreur (avec tous les "at" justement et les "caused by" eventuels).

    Sinon "bluetooth" est une classe d'activité... Elle ne peut donc pas être référencée simplement de cette manière (au passage, en Java, les types: classes, enums, interfaces, doivent commencer par une majuscule, à l'inverse des membres que ce soient des variables ou des fonctions).

    De plus la référence "bt" n'est jamais initialisée (donc vaut null). L'appel à bt.write("mon message"); va probablement lancer une exception "NullPointerException" (à moins bien sur que l'on aie qu'une partie du code).
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  3. #3
    Candidat au Club
    Inscrit en
    Avril 2013
    Messages
    3
    Détails du profil
    Informations forums :
    Inscription : Avril 2013
    Messages : 3
    Points : 3
    Points
    3
    Par défaut
    Bonjour,
    Merci pour votre aider
    bon lorsque je mes l'exception et initialiser l'appel de class Bluetooth = null
    le méthode write n'est pas exécuté elle passe à l'exception
    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
     
    public class Touch extends Activity implements OnClickListener {
     
        Button button;
        Bluetooth bt=null;
     
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.touchpad);
    button =((Button)this.findViewById(R.id.button2));
    button.setOnClickListener(this);
     
    	}
     
    	@Override
    	public void onClick(View arg0) {
    		try{
               bt.write("mon message".getBytes());    
    	}catch(NullPointerException e)
    	{
     
     
    	}
    	}
     
     
    }
    et ici la méthode write de la class Bluetooth
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
    public void write(byte[] se) {
          ConnectedThread r;
       Synchronized(this){
      r=mConnectedThread;
    }	
     r.write(se);
     
    	}
    et Merci d'avance

  4. #4
    Expert éminent

    Homme Profil pro
    Ingénieur systèmes et réseaux
    Inscrit en
    Février 2007
    Messages
    4 253
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Ingénieur systèmes et réseaux
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2007
    Messages : 4 253
    Points : 7 618
    Points
    7 618
    Billets dans le blog
    3
    Par défaut
    Je vous suggère de lire les cours / tutoriaux sur Java disponible ici...

    En particulier sur les classes et les instances:
    http://java.developpez.com/livres/ja...e=classes#LV-A
    N'oubliez pas de cliquer sur mais aussi sur si un commentaire vous a été utile !
    Et surtout

  5. #5
    Candidat au Club
    Inscrit en
    Avril 2013
    Messages
    3
    Détails du profil
    Informations forums :
    Inscription : Avril 2013
    Messages : 3
    Points : 3
    Points
    3
    Par défaut
    Bonjour,
    merci de m'aider
    je dois mettre le la méthode write en static et merci

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 1
    Dernier message: 20/06/2014, 11h04
  2. Appeler une méthode Action d'un autre controller
    Par xtrimsky dans le forum MVC
    Réponses: 13
    Dernier message: 26/05/2008, 23h14
  3. Problème pour appeler une méthode d'une autre classe
    Par tse_tilky_moje_imja dans le forum Général Python
    Réponses: 7
    Dernier message: 03/03/2006, 13h33
  4. [POO]Appelé une méthode d'une classe mère
    Par LE NEINDRE dans le forum Langage
    Réponses: 2
    Dernier message: 14/12/2005, 14h44
  5. Réponses: 2
    Dernier message: 31/08/2005, 16h12

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