0

I am trying to use a Spinner to select a user name and then open a new conversation layout when the client clicks the start chat button. I am sure that the button code is correct but my spinner cause my application crash.

myListView.setOnItemSelectedListener(new OnItemSelectedListener () {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, 
                               int pos, long id) {
        // An item was selected. You can retrieve the selected item using
        name1 = parent.getItemAtPosition(pos).toString();   
        CStart = (Button) findViewById(R.id.Start) ;
        CStart.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                open(v);
            }
        });
    }
    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
        }
    });

The open method:

protected void open(View v) {
    Intent i = new Intent(this, MainActivity2.class);
    i.putExtra("message", name1);
    startActivityForResult(i, 1);
}

Can you help me to fix my code?

Logcat :

03-24 19:48:32.967: E/AndroidRuntime(23058): FATAL EXCEPTION: main 
03-24 19:48:32.967: E/AndroidRuntime(23058): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javachat/com.example.javachat.MainActivity}: java.lang.IllegalArgumentException: Receiver not registered: com.example.javachat.MainActivity$1@418afa30 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.access$600(ActivityThread.java:162) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.os.Handler.dispatchMessage(Handler.java:107) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.os.Looper.loop(Looper.java:194) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.main(ActivityThread.java:5371) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at java.lang.reflect.Method.invokeNative(Native Method) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at java.lang.reflect.Method.invoke(Method.java:525) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 03-24 19:48:32.967: E/AndroidRuntime(23058):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at dalvik.system.NativeStart.main(Native Method) 
03-24 19:48:32.967: E/AndroidRuntime(23058): Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.example.javachat.MainActivity$1@418afa30 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:657)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1442) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:445) 03-24 19:48:32.967: E/AndroidRuntime(23058):  at com.example.javachat.MainActivity.onDestroy(MainActivity.java:229) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at com.example.javachat.MainActivity.onCreate(MainActivity.java:136) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.Activity.performCreate(Activity.java:5122) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1084) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307) 
03-24 19:48:32.967: E/AndroidRuntime(23058):... 11 more

manifest code :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.javachat"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >



        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

    </application>

</manifest>

my .java file if you need to check any thing else like imports and methods....

package com.example.javachat;

import java.util.Set;

import android.app.Activity;
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.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
   private static final int REQUEST_ENABLE_BT = 1;
   private Button onBtn;
   private Button offBtn;
   private Button listBtn;
   private Button findBtn;
   private TextView text;
   private Button CStart ;
   private String name1 ;
   private BluetoothAdapter myBluetoothAdapter;
   private Set<BluetoothDevice> pairedDevices;
   private Spinner myListView;
   private ArrayAdapter<String> BTArrayAdapter;

  //*******************************MAIN************************
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main2);

      // take an instance of BluetoothAdapter - Bluetooth radio
      myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
      if(myBluetoothAdapter == null) {
          onBtn.setEnabled(false);
          offBtn.setEnabled(false);
          listBtn.setEnabled(false);
          findBtn.setEnabled(false);
          CStart.setEnabled(false);
          text.setText("Status: not supported");

          Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
                 Toast.LENGTH_LONG).show();
      } else {
          text = (TextView) findViewById(R.id.text);
          onBtn = (Button)findViewById(R.id.turnOn);
          onBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                on(v);
            }
          });

          offBtn = (Button)findViewById(R.id.turnOff);
          offBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                off(v);
            }
          });

          //*********************************************************
          listBtn = (Button)findViewById(R.id.paired);
          listBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                list(v);
            }
          });

          //**********************************************************

         myListView.setOnItemSelectedListener(new OnItemSelectedListener (){

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, 
                    int pos, long id) {             
                // An item was selected. You can retrieve the selected item using
                 name1= new String (parent.getItemAtPosition(pos).toString());  
                 CStart = (Button) findViewById(R.id.Start) ;
                  CStart.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            open(v);
                            }
                        });
            }


           public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
                Toast.makeText(getApplicationContext(),"Select a device" ,
                         Toast.LENGTH_LONG).show();
            }
          });

          //***********************************************************
          findBtn = (Button)findViewById(R.id.search);
          findBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                find(v);
            }
          });
         //***********************************************************
          myListView = (Spinner)findViewById(R.id.listView1);
          // create the arrayAdapter that contains the BTDevices, and set it to the ListView
          BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
          BTArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
          myListView.setAdapter(BTArrayAdapter);  

      }
   }
        //**********************************METHODE***********************


   protected void open(View v) {
    // TODO Auto-generated method stub
       Intent i = new Intent(this ,MainActivity2.class);
     //  i.putExtra("message",name1);
        startActivityForResult(i, 1);

}


public void on(View view){
      if (!myBluetoothAdapter.isEnabled()) {
         Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);

         Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
                 Toast.LENGTH_LONG).show();
      }
      else{
         Toast.makeText(getApplicationContext(),"Bluetooth is already on",
                 Toast.LENGTH_LONG).show();
      }
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       // TODO Auto-generated method stub
       if(requestCode == REQUEST_ENABLE_BT){
           if(myBluetoothAdapter.isEnabled()) {
               text.setText("Status: Enabled");
           } else {   
               text.setText("Status: Disabled");
           }
       }
   }

   public void list(View view){
      // get paired devices
      pairedDevices = myBluetoothAdapter.getBondedDevices();

      // put it's one to the adapter
      for(BluetoothDevice device : pairedDevices)
          BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());

      Toast.makeText(getApplicationContext(),"Show Paired Devices",
              Toast.LENGTH_SHORT).show();

   }

   final BroadcastReceiver bReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                 // Get the BluetoothDevice object from the Intent
                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                 // add the name and the MAC address of the object to the arrayAdapter
                 BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                 BTArrayAdapter.notifyDataSetChanged();
            }
        }
    };

   public void find(View view) {
       if (myBluetoothAdapter.isDiscovering()) {
           // the button is pressed when it discovers, so cancel the discovery
           myBluetoothAdapter.cancelDiscovery();
       }
       else {
            BTArrayAdapter.clear();
            myBluetoothAdapter.startDiscovery();

            registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));    
        }    
   }

   public void off(View view){
      myBluetoothAdapter.disable();
      text.setText("Status: Disconnected");

      Toast.makeText(getApplicationContext(),"Bluetooth turned off",
              Toast.LENGTH_LONG).show();
   }

   @Override
   protected void onDestroy() {
       // TODO Auto-generated method stub
       super.onDestroy();
       unregisterReceiver(bReceiver);
   }


}
Wael Golli
  • 87
  • 2
  • 8

2 Answers2

0

Exception clearly states the following:

Receiver not registered: com.example.javachat.MainActivity$1@418afa30

Crash happens here:

03-24 19:48:32.967: E/AndroidRuntime(23058):at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:445)
03-24 19:48:32.967: E/AndroidRuntime(23058):  at com.example.javachat.MainActivity.onDestroy(MainActivity.java:229) 
03-24 19:48:32.967: E/AndroidRuntime(23058):at com.example.javachat.MainActivity.onCreate(MainActivity.java:136)

You have unregisterReceiver at the onDestroy, but you have no place, where you are registering it. Also you would like to take a look here, because onItemSelected will be called for Spinner without user action.

But it is not the end. The BroadcastReceiver declaration is wrong. Since you are using broadcast receiver locally, binding it to the Activity lifecycle, you should use LocalBroadcastManager, to register/unregister at the onCreate/onDestroy (or other lifecycle callbacks, depends on your needs). Thus, the following declaration in manifest makes no sense:

 <receiver android:name=".bReceiver">
 </receiver>

Because you have no class called bReceiver, you have a local variable (which should be actually made a class member) bReceiver, which points to an instance of BroadcastReceiver class.

Community
  • 1
  • 1
nikis
  • 11,166
  • 2
  • 35
  • 45
  • i added receiver to android manifest following some replays ...and if you can make it easier for me to understand it will be great, i'am still new in this language and i didn't get it how to solve my problem. – Wael Golli Mar 25 '15 at 19:46
  • @WaelGolli you can read this http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html tutorial – nikis Mar 25 '15 at 19:49
  • i think i got it ,i'm not getting the contextwrapper /ondestroy/oncreat/ log cat now but the app still crash – Wael Golli Mar 25 '15 at 23:05
  • i managed to make it work all the app it was my fault because 'mylistview' used on setOnItemSelectedListener before i write "myListView = (Spinner)findViewById(R.id.listView1);" @nikis – Wael Golli Mar 25 '15 at 23:28
-1

if clicking on the Button is causing your crash, then the reason is -

you have set a method local anonymous inner class object as listener in your onItemSlected(). that object will be destroyed when the method execution is finished.

So when the onItemSelected is finished, your listener object is set properly. but by the time when button is being clicked, that saved listener object is invoked which is actually cleared by garbage collector.

you shouldn't set the listener this way. you can easily set the listener outside of your item click listener if I did understand your requirement correctly.

Amit K. Saha
  • 5,871
  • 2
  • 27
  • 35
  • I tried Button Code without using Spinner code and worked fine , then i did it in other way by using Spinner code and without Button code and it caused a crash. – Wael Golli Mar 24 '15 at 17:17
  • can you share your latest code on which you are getting crash and the stack trace from log? – Amit K. Saha Mar 24 '15 at 17:45