首页 文章

订阅时,Android附近的API NullPointerException

提问于
浏览
1

我正在尝试使用Nearby Messages API for Android创建一个应用程序但是当我尝试运行应用程序时,我得到一个nullpointerexception,指的是我的代码的"subscribe"部分 . 我一直关注此处的Google文档:https://developers.google.com/nearby/messages/android/get-started . 发布活动仅发布Hello World,而不是从BroadcastReceiver接收的数据 .

我有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>

1 回答

  • 1

    你的订阅在这里抛出空指针异常:

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

    基于此,我们知道空指针必须来自 nGoogleApiClientmMessageListeneroptions . 当我滚动浏览 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)
    

相关问题