Android附近的API NullPointerException在订阅

问题描述:

我试图创建一个应用程序使用Android的Nearby Messages API,但是当我尝试运行该应用程序时,我得到一个nullpointerexception引用我的代码的“订阅”部分。我一直在关注Google文档:https://developers.google.com/nearby/messages/android/get-started。 发布活动只发布Hello World,而不是从BroadcastReceiver收到的数据。Android附近的API NullPointerException在订阅

我有2个活动,一个发布数据,另一个订阅这些数据。 以下是发布活动。如果我遗漏了任何东西,请告诉我。

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.support.annotation.NonNull; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.nearby.Nearby; 
import com.google.android.gms.nearby.messages.Message; 

import static com.example.mark.prototype9.MainActivity.RETURN; 


public class MusicPlayingActivity extends AppCompatActivity implements 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener 
{ 

public static final String TAG = "MusicPlayingActivity"; 
public static final String SERVICECMD = "com.android.music.musicservicecommand"; 

GoogleApiClient mGoogleApiClient; 
Message mActiveMessage; 

TextView track1;   

TextView artist; 
TextView album; 
TextView title; 
Button songfeed; 


private void publish(String message) { 
    Log.i(TAG, "Publishing message: " + message); 
    mActiveMessage = new Message(message.getBytes()); 
    Nearby.Messages.publish(mGoogleApiClient, mActiveMessage); 
} 

private void unpublish() { 
    Log.i(TAG, "Unpublishing."); 
    if (mActiveMessage != null) { 
     Nearby.Messages.unpublish(mGoogleApiClient, mActiveMessage); 
     mActiveMessage = null; 
    } 
} 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    mGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(Nearby.MESSAGES_API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .enableAutoManage(this, this) 
      .build(); 

    setContentView(R.layout.activity_music_playing); 
    artist = (TextView) findViewById(R.id.artist); 
    album = (TextView) findViewById(R.id.album); 
    title = (TextView) findViewById(R.id.title); 
    songfeed = (Button) findViewById(R.id.songfeed); 

    track1 = (TextView) findViewById(R.id.track1); 

    IntentFilter iF = new IntentFilter(); 
    iF.addAction("com.android.music.metachanged"); 
    iF.addAction("com.android.music.playstatechanged"); 
    iF.addAction("com.android.music.playbackcomplete"); 
    iF.addAction("com.android.music.queuechanged"); 
    iF.addAction("com.htc.music.metachanged"); 
    iF.addAction("fm.last.android.metachanged"); 
    iF.addAction("com.sec.android.app.music.metachanged");    
    iF.addAction("com.nullsoft.winamp.metachanged"); 
    iF.addAction("com.amazon.mp3.metachanged"); 
    iF.addAction("com.miui.player.metachanged"); 
    iF.addAction("com.real.IMP.metachanged"); 
    iF.addAction("com.sonyericsson.music.metachanged"); 
    iF.addAction("com.rdio.android.metachanged"); 
    iF.addAction("com.samsung.sec.android.MusicPlayer.metachanged"); 
    iF.addAction("com.andrew.apollo.metachanged"); 


    registerReceiver(mReceiver, iF);         


    songfeed.setOnClickListener(new View.OnClickListener(){   
     @Override 
     public void onClick (View v){ 
       Intent getResult = new Intent(getApplicationContext(), MainActivity.class); 
       startActivityForResult(getResult, RETURN); 
      } 

    }); 
} 



private BroadcastReceiver mReceiver = new BroadcastReceiver() {  
    @Override 
    public void onReceive(Context context, Intent intent) 
    { 
     String action = intent.getAction(); 
     String cmd = intent.getStringExtra("command"); 
     Log.v("tag ", action + "/" + cmd); 
     String artists = intent.getStringExtra("artist");    
     String albums = intent.getStringExtra("album"); 
     String tracks = intent.getStringExtra("track"); 
     Log.v("tag", artists + ":" + albums + ":" + tracks); 

     artist.setText(artists); 
     album.setText(albums);          
     title.setText(tracks); 



     unregisterReceiver(mReceiver); 

    } 

}; 

@Override 
public void onConnected(Bundle connectionHint) { 
    publish("Hello World!"); 
    //track1.setText(tracks); 
} 

@Override 
public void onStop() { 
    unpublish(); 
    super.onStop(); 
} 



@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

} 

的订阅活动:

import android.content.Intent; 
import android.os.Bundle; 
import android.support.annotation.NonNull; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.nearby.Nearby; 
import com.google.android.gms.nearby.messages.Message; 
import com.google.android.gms.nearby.messages.MessageListener; 
import com.google.android.gms.nearby.messages.SubscribeOptions; 

import static com.example.mark.prototype9.MainActivity.RETURN; 
import static com.example.mark.prototype9.MusicPlayingActivity.TAG; 


public class SubActivity extends AppCompatActivity implements 
    GoogleApiClient.ConnectionCallbacks, 
    GoogleApiClient.OnConnectionFailedListener { 


GoogleApiClient nGoogleApiClient; 
MessageListener mMessageListener; 
SubscribeOptions options; 


//TextView title; 

TextView track1; 
TextView album1; 
TextView artist1; 

TextView track2; 
TextView album2; 
TextView artist2; 

TextView track3; 
TextView album3; 
TextView artist3; 

Button back; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_pub_sub); 

    nGoogleApiClient = new GoogleApiClient.Builder(this) 
      .addApi(Nearby.MESSAGES_API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .enableAutoManage(this, this) 
      .build(); 


       //data to send 
    //title = (TextView) findViewById(R.id.title); 
    //album 
    //track 

       //data to receive 
    track1 = (TextView) findViewById(R.id.track1); 
    album1 = (TextView) findViewById(R.id.album1); 
    artist1 = (TextView) findViewById(R.id.artist1); 

    track2 = (TextView) findViewById(R.id.track2); 
    album2 = (TextView) findViewById(R.id.album2); 
    artist2 = (TextView) findViewById(R.id.artist2); 

    track3 = (TextView) findViewById(R.id.track3); 
    album3 = (TextView) findViewById(R.id.album3); 
    artist3 = (TextView) findViewById(R.id.artist3); 

    back = (Button) findViewById(R.id.back); 


    mMessageListener = new MessageListener() { 
     @Override 
     public void onFound(Message message) { 
      String messageAsString = new String(message.getContent()); 
      Log.d(TAG, "Found message: " + messageAsString); 
     } 

     @Override 
     public void onLost(Message message) { 
      String messageAsString = new String(message.getContent()); 
      Log.d(TAG, "Lost sight of message: " + messageAsString); 
      track1.setText("this is "+ messageAsString); 
     } 
    }; 

    back.setOnClickListener(new View.OnClickListener(){   //commanding back button to return user to MainActivity 
     @Override 
     public void onClick (View v){ 
      Intent getResult = new Intent(getApplicationContext(), MainActivity.class); 
      startActivityForResult(getResult, RETURN); 
     } 
}); 

} 

// Subscribe to receive messages. 
private void subscribe() { 
    try{ 
    Log.i(TAG, "Subscribing."); 
    Nearby.Messages.subscribe(nGoogleApiClient, mMessageListener, options); 
    //convert message to string? 
} 
    catch (NullPointerException n){ 
     n.printStackTrace(); 
    } 
} 

private void unsubscribe() { 
    Log.i(TAG, "Unsubscribing."); 
    Nearby.Messages.unsubscribe(nGoogleApiClient, mMessageListener); 
} 



    //put subscribed data in try/catch statement- catch unknown track/album/artist display as textview 



@Override 
public void onConnected(Bundle b) { 
    subscribe(); 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onStop() { 
    unsubscribe(); 
    super.onStop(); 
} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 
} 

这里是logcat的

02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:    java.lang.NullPointerException: null reference 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.common.internal.zzaa.zzy(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.nearby.messages.internal.zzs.subscribe(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.example.mark.prototype9.SubActivity.subscribe(SubActivity.java:113) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.example.mark.prototype9.SubActivity.onConnected(SubActivity.java:134) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.common.internal.zzk.zzp(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.internal.zzrd.zzn(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.internal.zzrb.zzass(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.internal.zzrb.onConnected(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.internal.zzrf.onConnected(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.internal.zzqr.onConnected(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.common.internal.zzj$1.onConnected(Unknown Source) 
    02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.common.internal.zze$zzj.zzavj(Unknown Source) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.common.internal.zze$zza.zzc(Unknown Source) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.common.internal.zze$zza.zzv(Unknown Source) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.common.internal.zze$zze.zzavl(Unknown Source) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at com.google.android.gms.common.internal.zze$zzd.handleMessage(Unknown Source) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at android.os.Handler.dispatchMessage(Handler.java:102) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at android.os.Looper.loop(Looper.java:211) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at android.app.ActivityThread.main(ActivityThread.java:5389) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at java.lang.reflect.Method.invoke(Native Method) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at java.lang.reflect.Method.invoke(Method.java:372) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020) 
    02-10 15:17:50.905 27479-27479/com.example.mark.prototype9 W/System.err:  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815) 
    02-10 15:18:44.327 27479-27490/com.example.mark.prototype9 W/art: Suspending all threads took: 13.193ms 
    02-10 15:18:50.934 27479-27479/com.example.mark.prototype9 I/MusicPlayingActivity: Unsubscribing. 
    02-10 15:18:50.936 27479-27479/com.example.mark.prototype9 D/NearbyMessagesClient: Emitting client lifecycle event ACTIVITY_STOPPED 
    02-10 15:18:50.936 27479-27479/com.example.mark.prototype9 D/NearbyMessagesClient: Emitting client lifecycle event CLIENT_DISCONNECTED 

以防万一,这里是我的清单,

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.INTERNET"/> 

<service android:name=".MediaPlaybackService"> 
    <intent-filter> 
     <action android:name="android.media.browse.MediaBrowserService" /> 
    </intent-filter> 
</service> 

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <meta-data 
     android:name="com.google.android.nearby.messages.API_KEY" 
     android:value="************" /> 

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

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity android:name=".MusicPlayingActivity" /> 
    <activity android:name=".SubActivity" /> 
    <activity android:name=".MusicMetaData"></activity> 
</application> 

您的订阅在这里抛出空指针异常:在此基础上

Nearby.Messages.subscribe(nGoogleApiClient, mMessageListener, options); 

,我们知道空指针必须来自nGoogleApiClientmMessageListener,或options。当我滚动onCreate时,我看到nGoogleClientmMessageListener被初始化,所以我在options上做了一个快速搜索。答对了!

下一次,我建议使用logcat,它告诉你从哪里找到你的问题和调查的确切路线。

02-10 15:17:50.904 27479-27479/com.example.mark.prototype9 W/System.err:  at com.example.mark.prototype9.SubActivity.subscribe(SubActivity.java:113) 
+0

谢谢!我确实使用logcat来查找哪条线路正在抛出异常,但我试过的任何东西都很短。对于我如何初始化选项有什么建议吗?选项是SubscribeOptions的一个实例。 – Mark

+0

@标记随着时间的推移,它会成为第二大自然,因为你在不同的情况下遇到这种情况,并且看到它只是另一个同样问题的实例。此外,您可以接受/ upvote我的答案作为解决方案。关于初始化'选项',我会看看android这个例子,如[this](https://developers.google.com/nearby/messages/android/get-beacon-messages) – iheanyi

+0

感谢您的帮助! – Mark