未知错误:java.lang.nullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4351751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:00:57  来源:igfitidea点击:

Unknown Error:java.lang.nullPointerException

javaandroid

提问by Patty

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:

我对开发 Android 应用程序很陌生,我希望我把它发布在正确的地方。我正在尝试学习如何让手机蓝牙连接到我的蓝牙模块。我正在尝试使用我在参考书中找到的代码,但它给了我一个错误。我以前用 Java 编写过,但我很难理解 Android 应用程序的结构。无论如何,我得到的错误是:

Unknown Error: java.lang.nullPointerException

未知错误: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.

就像我说的那样,我对此很陌生,所以如果这没有多大意义,我深表歉意,但任何帮助将不胜感激。

回答by live-love

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).

在我的情况下,它与我引用了一个未使用的项目 appcompat_v7(这是一个兼容库,用于操作栏在较旧的 android 上工作)的事实有关。

How I solved it:

我是如何解决的:

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

右键单击项目,属性,在 Android 选项卡上,删除对库的引用。

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.

右键单击,将现有项目导入 WorkSpace,选择项目文件夹。

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

然后我重新构建了它,出现了一些错误,styles.xml 文件中缺少一些资源。

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

我删除了styles.xml 文件,因为我不需要它们。

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

我从 androidmanifest.xml 中删除了这个条目:android:theme="@style/AppTheme"。

回答by Kr1z

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..

尝试逐步调试它。这样你就会找到 NullPointerException 的原因。某些访问的字段可能为空。一旦你知道哪个字段,你就可以通过给该字段一个默认值来防止 NullPointerException ..

回答by cV2

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.

基本上一个项目被收录两次。像这样的错误消息也只发生在 Android ADT Eclipse Version 上

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

基本上,有
Project A -> Needing Library B
但也有
Project A -> Needing Dependency C

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

但此外,
依赖 C ->依赖于库 B

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

所以图书馆 B 来了两次。
希望解决方案很清楚,这就是我的问题:)

Hope it helps :) Cheers, Mike

希望它有帮助:) 干杯,迈克

回答by Abhilasha

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

右键单击项目 -> 属性 -> android -> 检查右侧窗口中的引用,查看引用中的所有库是否都存在于工作区中并且没有关闭

回答by user531069

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

从工作区中删除项目并再次导入它是解决此问题的最佳方法(如果 log cat 为空)。

回答by naren

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.

要快速摆脱空指针异常,您可以试试这个。
退出 Eclipse
打开 .project 文件并删除该部分。
重新启动 eclipse、clean 和 build
您现在可以看到实际的错误。您现在可以在项目属性中修复它。

Good luck!

祝你好运!

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

学分:http: //blog.thehappydeveloper.com/?p= 112

回答by GKeps

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
  1. 打开我的 .project 文件并删除不正确链接库的条目
  2. 打开 .classpath 文件并删除对在步骤 1 中删除的相同错误链接库的引用

回答by user1306828

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

检查您的项目文件夹中的 project.properties 它可能包含无效条目

回答by Hamlet Kraskian

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.
  • 右键单击项目名称
  • 点击属性
  • 选择安卓
  • 并在图书馆的部分检查无效参考。
  • 如果有一个关闭的项目(例如 android appcompat )尝试打开它。