Unknown error: java.lang.nullPointerException

I am very new to developing Android applications and I hope that I put this in the right place. I am trying to learn how to connect a Bluetooth phone to my Bluetooth module. I am trying to use the code that I found in the reference, but it gives me an error. I wrote in Java before, but it's hard for me to understand the structure of an Android application. In any case, I get the error:

Unknown error: java.lang.nullPointerException

Maybe I forgot to import the library I need, or did I make a packaging error when creating 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> 

As I said, I am very new to this, so I apologize if this does not make much sense, but any help would be greatly appreciated.

+8
java android
source share
9 answers

In my case, this is due to the fact that I had a link to the unused appcompat_v7 project (this is a compatibility library for the action bar for working with older Android).

How I decided it:

Right-click on the "Properties" project on the "Android" tab, remove the link to the library.

All projects in the package explorer were deleted (they did not delete them from the disk).

Then I imported the project again, for example:

Right-click, import, existing projects in WorkSpace, select the project folder.

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

I deleted the styles.xml files since I do not need them.

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

+3
source share

Try debugging it step by step. This way you will find the reason for the NullPointerException exception. Some available field is likely to be null. Once you know which field, you can prevent a NullPointerException by specifying the specified field by default.

+2
source share

For me it was a problem with addiction,

basically one project was included twice . An error message like this also happened with the Android ADT Eclipse Version .

In principle, there was
Project A → Required Library B.
But there was
Project A → Required Dependency C.

But also
The C dependency also had a dependency on library B.

So library B has been there twice.
Hope the solution is clear, it was a problem for me :)

Hope this helps :) Hooray, Mike

+1
source share

Right click on the project -> properties -> android -> check the links in the right window, see if there are all the libraries in the link in the workspace, and none of them are closed

+1
source share

Removing a project from the workspace and re-importing it is the best way to fix this (if the log code is empty).

0
source share

Just fixed this problem in my environment. I had a resource (source code) associated with my project. When I re-opened the project in a different workspace, it could not open the files.

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

Good luck

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

0
source share

I was able to fix this:

  • Opening my .project file and deleting the entry in the wrong linked library
  • Opening the .classpath file and deleting the link to the same incorrectly linked library that was deleted in step 1
0
source share

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

0
source share

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

  • right click project name
  • click on properties
  • select android
  • and in the library part check the invalid link.
  • and if there is a closed project (for example, android appcompat), try opening it.
0
source share

Source: https://habr.com/ru/post/649822/


All Articles