9

I am very new to developing Android apps, and I hope I am posting this in the right place. I am trying learn how to get the phone Bluetooth to connect to my Bluetooth module. I am trying to use code that I found in a reference book, but it is giving me an error. I have written in Java before but I am having a hard time understanding the structure of an Android app. Anyway the error I am getting is:

Unknown Error: java.lang.nullPointerException

Am I maybe forgetting to import a library that I need, or did I make a packaging mistake when I created the project?

Here is the code:

package android.app.bluetooth;
//import java.io.InputStream;
//import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;
import java.io.IOException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.os.Handler;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
//import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;    
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class bluetooth extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Get the bluetooth adapter (phone)
    configureBluetooth();

    //Setup ListView of discovered devices
    setupListView();

  //Setup search button
    setupSearchButton();

    //Setup listen button
    setupListenButton();
}

private BluetoothAdapter bluetooth;
private BluetoothSocket socket;
private UUID uuid = UUID.fromString("985c75a3-66ae-4b5b-9fac-894659d6f6ee");
private void configureBluetooth(){
     BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
     }

//Create switchUI method that will be called once a connection is 
//established to enable views for reading and writing messages  
private ListView list;
private void switchUI(){
    final TextView messageText = (TextView)findViewById(R.id.text_messages);
    final EditText textEntry = (EditText)findViewById(R.id.text_message);

    messageText.setVisibility(View.VISIBLE);
    list.setVisibility(View.GONE);
    textEntry.setEnabled(true);
    }

//Create server listener.  Listen button will prompt user to enable discovery
//When discovery window returns, open bluetooth socket to listen for connection       requests for discovery duration
//Once a connection has been made, make a call to switchUI 

private static int DISCOVERY_REQUEST = 1;
private void setupListenButton(){
 Button listenButton = (Button)findViewById(R.id.button_listen);
 listenButton.setOnClickListener(new OnClickListener(){
  public void onClick(View view){
   Intent disc;
   disc = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
   startActivityForResult(disc, DISCOVERY_REQUEST);
      }
     });
    }

//Find out if user has accepted or rejected the request

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if(requestCode == DISCOVERY_REQUEST){
     boolean isDiscoverable = resultCode > 0;
     if (isDiscoverable){
      String name = "bluetoothserver";
      try{
       final BluetoothServerSocket btserver =    bluetooth.listenUsingRfcommWithServiceRecord(name, uuid);
       AsyncTask<Integer, Void, BluetoothSocket> acceptThread = new AsyncTask<Integer, Void, BluetoothSocket>(){
        @Override
        protected BluetoothSocket doInBackground(Integer ... params){
         try{
          socket = btserver.accept(params[0]*1000);
          return socket;
          } catch (IOException e){
           Log.d("BLUETOOTH", e.getMessage());
          }
          return null;
         }
         @Override
         protected void onPostExecute(BluetoothSocket result){
          if (result != null)
           switchUI();
         }
        };
        acceptThread.execute(resultCode);
       } catch (IOException e){
        Log.d("BLUETOOTH", e.getMessage());
        }
      }
      //int discoverableDuration = resultCode;
     }
    }

//Provide a means for client device to search for listening server
private ArrayAdapter<BluetoothDevice> aa;
private ArrayList<BluetoothDevice> foundDevices;
private void setupListView(){
    aa = new ArrayAdapter<BluetoothDevice>(this, android.R.layout.simple_list_item_1, foundDevices);
    list = (ListView)findViewById(R.id.list_discovered);
    list.setAdapter(aa);

    //Include onItemClickListener that will attempt to asynchronously initiate a client-side connection
    //with the selected remote Bluetooth Device
    //If successful, keep a reference to the socket it creates and make a call to switchUI
    list.setOnItemClickListener(new OnItemClickListener() {
     public void onItemClick(AdapterView<?> arg0, View view, int index, long arg3){
      AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>(){
       @Override
       protected Void doInBackground(Integer ... params){
        try{
         BluetoothDevice device = foundDevices.get(params[0]);
         socket = device.createRfcommSocketToServiceRecord(uuid);
         socket.connect();
        } catch(IOException e){
         Log.d("BLUETOOTH_CLIENT", e.getMessage());
         }
         return null;
        }

        @Override
        protected void onPostExecute(Void result){
         switchUI();
        }
       };
       connectTask.execute(index);
      }
     });
    }

//Create a broadcast receiver that listens for Bluetooth Device discovery broadcasts,
//adds each discovered device to the array of found devices and notifies the Array  Adapter
//Discover remote bluetooth devices
BroadcastReceiver discoveryResult = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent){
 //String remoteDeviceName = intent.getStringName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
 BluetoothDevice remoteDevice; //remote bluetooth device
 remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
 if(bluetooth.getBondedDevices().contains(remoteDevice)){
  foundDevices.add(remoteDevice);
  aa.notifyDataSetChanged();
  }
 }
};

    //Register Broadcast Receiver and initiate discovery session
    private void setupSearchButton(){
     Button searchButton = (Button)findViewById(R.id.button_search);

     searchButton.setOnClickListener(new OnClickListener(){
      public void onClick(View view){
       registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));

       if (!bluetooth.isDiscovering()){
        foundDevices.clear();
        bluetooth.startDiscovery();
       }
      }
     });
    }
}

This is the layout file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
 android:id="@+id/text_message"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentBottom="true"
 android:enabled="false"
/>
<Button
 android:id="@+id/button_search"
 android:text="Search for listener"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_above="@id/text_message"
/>
<Button
 android:id="@+id/button_listen"
 android:text="Listen for connection"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:layout_above="@id/button_search"
/> 
<ListView
 android:id="@+id/list_discovered"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:layout_above="@id/button_listen"
 android:layout_alignParentTop="true"
/>
<TextView 
android:id="@+id/text_messages" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent"
android:layout_above="@id/button_listen"
android:layout_alignParentTop="true" 
android:visibility="gone"
/>
</RelativeLayout>

and here is the manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  android:versionCode="1"
  android:versionName="1.0" package="android.app.bluetooth">
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".bluetooth"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
</manifest> 

Like I said I am very new to this so I apologize if this doesn't make much sense but any help would be greatly appreciated.

live-love
  • 48,840
  • 22
  • 240
  • 204
Patty
  • 99
  • 1
  • 1
  • 2
  • 4
    You are posting to the right place. More importantly we need to see the stack trace that results in the nullPointerException. Please update the question with the stack trace. (If you were missing an import or reference then the program wouldn't compile.) – cfeduke Dec 04 '10 at 03:23
  • Forgive me but how do I do that? I tried adding Thread.dumpStack(); but when I try to run the program it says 'Your project contains error(s) please fix them before running your application'. – Patty Dec 04 '10 at 04:15
  • 1
    add the error dump from logcat – Chris Stratton Dec 04 '10 at 04:53
  • 1
    It should already print the stacktrace in your logcat. How do you know it's a nullpointerexception if you're not seeing a stacktrace. – Falmarri Dec 04 '10 at 04:55
  • It's not under logcat it's just under the 'Problems' tab. It just says 'Unknown Error:java.lang.nullPointerException Location:Unknown. I don't know how to add something to the logcat if I can't even get the code to run. There's nothing in the logcat right now its blank. – Patty Dec 04 '10 at 06:33
  • I'm sorry I feel like I'm probably making a really stupid but minor mistake, but I just can't figure it out : ( – Patty Dec 04 '10 at 06:36
  • All I did was change the package name and now it compiles and runs with no errors. I knew it had to be something dumb like that. But now I'm trying to test it out on the phone, instead of the emulator, and I can't get it to recognize the phone. I installed the usb driver and enabled usb on the phone. The documentation says that when I run the program it should prompt me to choose the device but it doesn't. Anyone else ever have this problem? – Patty Dec 04 '10 at 08:26
  • If patty's problem is the same as mine, they're talking about this error occuring at build time: [2010-12-13 21:27:41 - MyApp] Unknown error: java.lang.NullPointerException There's no stack trace in the console. Just that one line. I imported an existing project, fixed the project properties, and tried to build clean. – Mark F Guerra Dec 14 '10 at 02:37

9 Answers9

4

In my case it had to do with the fact that I had a reference to an unused project, appcompat_v7 (this is a compatibility library for the action bar to work on older android).

How I solved it:

Right clicked on project, Properties, on Android tab, removed reference to library.

Deleted all the projects in Package Explorer (did not delete them from the disk).

Then I imported my project back again, like this:

Right click, Import, Existing Projects into WorkSpace, select the project folder.

Then I rebuilt it, and there were some errors, some missing resources in styles.xml files.

I deleted the styles.xml files, since I didn't need them.

I deleted this entry from androidmanifest.xml: android:theme="@style/AppTheme".

live-love
  • 48,840
  • 22
  • 240
  • 204
  • Bingo! 12 years later, forgetting completely what-when-why in my project, that was indeed the solution for my own "Unknown Error NPE": Right-click project > `Properties` > `Android tab` (2 panes: Target & Library) > `Library` (list of referenced libraries) > Select the one no longer used and click the `Remove` button. – WebViewer Dec 04 '22 at 08:46
2

Try debugging it step by step. That way you'll find the cause of the NullPointerException. Some accessed field will probably be null. Once you know which field, you can prevent the NullPointerException by giving said field a default value..

Kr1z
  • 349
  • 3
  • 6
1

For me it was a dependency problem,

basically one project was included two times. The error message like this also only happened with Android ADT Eclipse Version.

Basically, there was
Project A -> Needing Library B.
But there was also
Project A -> Needing Dependency C.

But Additionally,
Dependency C -> also had dependency to Library B.

So Library B was there two times.
Hope the solution is clear, that was the problem for me :)

Hope it helps :) Cheers, Mike

cV2
  • 5,229
  • 3
  • 43
  • 53
1

Right click on project -> properties ->android ->check references in right window see if all libraries in reference are present in workspace and none is closed

Abhilasha
  • 11
  • 3
0

check your project.properties inside your project folder it may have invalid entries

user1306828
  • 715
  • 7
  • 14
0

I had the same problem. It was from a closed library project which was referenced from my project. So

  • right click on project name
  • click on properties
  • select android
  • and in library's part check for an invalid reference.
  • and if there is a closed project (such as android appcompat ) try to open it.
Hamlet Kraskian
  • 683
  • 9
  • 11
0

deleting project from workspace and importing it again is the best way to fix this (if log cat is empty)..

user531069
  • 985
  • 8
  • 28
0

Just fixed this issue in my environment. I had a resource (source code) linked to my project. When I reopened the project in a different workspace it failed to open the files.

To quickly get rid of the null pointer exception you can try this.
Exit Eclipse
Open the .project file and delete the section.
Restart eclipse, clean and build
You can now see the actual error. You can now fix it in the project properties.

Good luck!

Credits: http://blog.thehappydeveloper.com/?p=112

naren
  • 71
  • 3
0

I was able to fix this by:

  1. Opening up my .project file and deleting an entry to an incorrect linked library
  2. Opening the .classpath file and removing the reference to the same incorrectly linked library as was deleted in step 1
GKeps
  • 456
  • 5
  • 6