Я пытаюсь создать приложение с помощью API сообщений для Android, но когда я пытаюсь запустить приложение, я получаю исключение nullpointer, ссылаясь на разделы «подписаться» моего кода. Я слежу за документацией Google здесь: https://developers.google.com/nearby/messages/android/get-started. Издательская деятельность публикует только Hello World, а не данные, полученные от BroadcastReceiver.Android API 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>
Спасибо! Я использовал логарифм, чтобы найти, какие строки выбрасывали исключение, но все, что я пробовал, оказалось коротким. Были бы предложения по поводу того, как я инициализирую варианты? Параметры являются экземпляром SubscribeOptions. – Mark
@Mark это станет второй природой с течением времени, когда вы столкнетесь с этим в разных ситуациях и увидите, что это просто еще один пример той же проблемы. Кроме того, вы можете принять/усовершенствовать мой ответ в качестве решения. Что касается инициализации 'options', я бы посмотрел на примеры Android, такие как [this] (https://developers.google.com/nearby/messages/android/get-beacon-messages) – iheanyi
Спасибо за вашу помощь! – Mark