ResultReceiver 给出 Nullpointer 异常

2024-04-18

我正在使用地理编码来检索纬度、经度值的地址。我在扩展 IntentService 的单独类中实现此地理编码。当我检索地址时,我想将其发送回原始主要活动,为此我使用 ResultReciever,并实际上遵循tutorial https://developer.android.com/training/location/display-address.html.

这是我用于 GeoCode 的类,即将 GPS 坐标传输到物理地址。调用函数时出现错误deliverResultToReceiver in onHandleIntent

public class FetchAddressIntentService extends IntentService {

    protected ResultReceiver mReceiver;


    public FetchAddressIntentService() {
        super("GPSGame");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());

        String errorMessage = "";

        // Get the location passed to this service through an extra.
        Location location = intent.getParcelableExtra(
                Constants.LOCATION_DATA_EXTRA);
        Log.e("LAT",Double.toString(location.getLatitude()));
        Log.e("LONG",Double.toString(location.getLongitude()));
        List<Address> addresses = null;   /*** ADDRESS CAN BE OF ANOTHER LIBRARY ***/

        try {
            addresses = geocoder.getFromLocation(
                    location.getLatitude(),
                    location.getLongitude(),
                    // In this sample, get just a single address.
                    1);
        } catch (IOException ioException) {
            // Catch network or other I/O problems.
              errorMessage = "service not available";
              Log.e("exception", errorMessage);

        } catch (IllegalArgumentException illegalArgumentException) {
            // Catch invalid latitude or longitude values.
            errorMessage = "IllegalArgumentException";
            Log.e("Exception", errorMessage + ". " +
                    "Latitude = " + location.getLatitude() +
                    ", Longitude = " +
                    location.getLongitude(), illegalArgumentException);

        }

     // Handle case where no address was found.
        if (addresses == null || addresses.size()  == 0) {
            if (errorMessage == "") {
                errorMessage = "no address found";
                Log.e("address", errorMessage);
            }
            deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage);
        }

        else {
            Address address = addresses.get(0);
            ArrayList<String> addressFragments = new ArrayList<String>();

            // Fetch the address lines using getAddressLine,
            // join them, and send them to the thread.
            for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                addressFragments.add(address.getAddressLine(i));
            }
            Log.i("address", "address found");
            deliverResultToReceiver(Constants.SUCCESS_RESULT,
                    TextUtils.join(System.getProperty("line.separator"), 
                            addressFragments));     TextUtils.join(System.getProperty("line.separator"),addressFragments));

        }

    }

    private void deliverResultToReceiver(int resultCode, String message) {
        Bundle bundle = new Bundle();
        bundle.putString(Constants.RESULT_DATA_KEY, message);
        mReceiver.send(resultCode, bundle);
    }

}

这是MainAcitivty我试图在其中获取地址的类。请注意,有一个私人课程AddressResultReceiver延伸ResultReciever too.

public class MainActivity extends Activity implements
ConnectionCallbacks, OnConnectionFailedListener, LocationListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        latitudeText = (TextView) findViewById(R.id.latitudeText);
        longitudeText = (TextView) findViewById(R.id.longitudeText);
        lastUpdateTimeText = (TextView) findViewById(R.id.lastUpdateText);
        buildGoogleApiClient(); 
    }

    protected void startIntentService() {
        Intent intent = new Intent(this, FetchAddressIntentService.class);
        intent.putExtra(Constants.RECEIVER, mResultReceiver);
        intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);
        startService(intent);
        AddressResultReceiver ar = new AddressResultReceiver(null);
        Bundle b = new Bundle();
        ar.onReceiveResult(Constants.SUCCESS_RESULT, b);
    }




    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();
        mGoogleApiClient.connect();

    }

    @SuppressLint("NewApi")
    @Override
    public void onConnected(Bundle connectionHint) {
        Toast.makeText(this, "onConnected", Toast.LENGTH_LONG).show();
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            String latitude = String.valueOf(mLastLocation.getLatitude());
            String longitude = String.valueOf(mLastLocation.getLongitude());
            latitudeText.setText("latitude: " + latitude);
            longitudeText.setText("longitude: " + longitude);
        }
        if (mLastLocation != null) {
            // Determine whether a Geocoder is available.
            if (!Geocoder.isPresent()) {
                Toast.makeText(this, "No geocoder available",
                        Toast.LENGTH_LONG).show();
                return;
            }    
            if (mAddressRequested) {
                startIntentService();
            }
        }

    }   

    private void updateUI() {
        latitudeText.setText(String.valueOf(mCurrentLocation.getLatitude()));
        longitudeText.setText(String.valueOf(mCurrentLocation.getLongitude()));
        lastUpdateTimeText.setText(mLastUpdateTime);
    }

    class AddressResultReceiver extends ResultReceiver {
        public AddressResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {

            // Display the address string
            // or an error message sent from the intent service.
            String mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
            Log.e("RESULT!!!", mAddressOutput);

            // Show a toast message if an address was found.
            if (resultCode == Constants.SUCCESS_RESULT) {
                ;
            }
        }
    }
}

当我调用私有方法时,出现空指针异常deliverResultToReciever。如果您能向我展示如何正确获取地址数据,我将不胜感激


未初始化mResultReceiver传递给 Intent Service 之前的对象。执行如下操作:

protected void startIntentService() {
        Intent intent = new Intent(this, FetchAddressIntentService.class);
        mResultReceiver = new AddressResultReceiver(new Handler());
         .... your code here
    }

并且还初始化mReceiver对象在FetchAddressIntentService通过让接收器进入类onHandleIntent method:

@Override
protected void onHandleIntent(Intent intent) {
  mReceiver = intent.getParcelableExtra(Constants.RECEIVER);
  //...your code here
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ResultReceiver 给出 Nullpointer 异常 的相关文章

  • 为什么 cordova.file.documentsDirectory 为空?

    我正在尝试使用 cordova plugin file transfer 在http ngcordova com docs plugins fileTransfer http ngcordova com docs plugins fileT
  • 在名称中使用时间戳时,Android Studio 在构建后无法启动应用程序

    我遇到了 gradle 和 Android Studio 的问题 该问题仅在 Android Studio 中构建时出现 BuildServer 和 Commandline 工作正常 applicationVariants all vari
  • 如何从一个活动中完成一系列开放的子活动?

    我正在尝试为我的应用程序制作一个退出按钮 无论如何 我能够跟踪我的应用程序中的所有活动实例 然后完成它们 但在某些情况下 仍有一些活动仍然存在 不知道怎么办 有没有什么方法可以杀死android中的特定应用程序 或者我可以通过任何其他方式退
  • OPENGL ES 不工作:无当前上下文

    我尝试了 OpenGL ES2 for Android 一书中所示的程序 但它不起作用 我已经在Odroid E 三星s3 三星y 三星star上进行了测试 the gl version suported returns 2 but i g
  • Android向后兼容技术

    我现在在开发基于最新 API 15 ICS 的 15 项活动 Android 应用程序方面取得了进展 现在我发现应用程序的主要功能主义者即使支持 android v4 也不向后兼容 例如 1 fragment事务动画 2 将StringSe
  • 在代码中旋转按钮(或其中的文本)

    我必须通过编码随机旋转按钮 或里面的文本 它是相同的 API级别低于11是否有button setRotate x 好吧 看了一下 答案是 很复杂 您可以使用旧的动画框架旋转按钮 例如像这样 Button button Button fin
  • 有没有办法将搜索栏添加到我的实际首选项屏幕?

    我一直看到有关添加您自己的搜索栏首选项的教程 但它不在我实际的 prefs xml 中 有什么方法可以在我的主偏好设置屏幕中添加一个 或者我必须将其分开 Google 似乎有 2 个滑块首选项 搜索栏首选项 https github com
  • Android 中的 java.util.Observable 是线程安全的吗?

    Android 中的 java util Observable 是线程安全的吗 这文档 http developer android com reference java util Observable html说只有deleteObser
  • 从 BroadcastReceiver 获取方法来更新 UI

    我正在尝试根据变量的变化更新用户界面BroadcastReceiver 因此 我需要调用一个扩展类的方法 以获取我提到的变量 BroadcastReceiver in MainActivity取决于但我无法以任何方式获得真正的返回值 扩展的
  • 无法在云控制台中启用 Maps SDK for Android

    我在云控制台中启用适用于 Android 的 Maps SDK 时遇到此问题 https console cloud google com https console cloud google com 它会抛出以下错误 附截图 我收到错误消
  • Android BLE 扫描在后台几分钟后停止

    当我为公司开发新冠肺炎接触者追踪应用程序时 我在后台遇到了 Android 扫描停止问题 这是我尝试过的 添加前台服务 禁用手机中所有与电池相关的优化选项 启用后台运行的应用程序 测试设备 搭载 Android 10 的 Galaxy S2
  • 如何在android中画一条曲线?

    我是 Android 新手 正在开发一个关于绘制线条的示例项目 我想画一条连接两点的曲线或高架线 x1 y1 and x2 y2 我试过canvas drawArc 方法 但是RectF内的值drawArc方法只是圆的 x y 中心点 它在
  • 如何知道用户是否在 Android 应用程序中输入了错误的密码(锁定屏幕)

    我正在开发一个 Android 应用程序 如果用户在 Android 锁定屏幕中输入错误的密码 则必须完成其中一项活动 例如 如果用户输入错误的密码 则会发送电子邮件 我将不胜感激任何帮助 提前致谢 Kshitij 锁屏在完全沙箱环境中运行
  • 使用 UPI url 调用 PSP 应用程序

    我正在尝试创建一个商家应用程序 它将根据 NPCI 的指南生成一个 url 此 url 将作为意图共享 并且 PSP 应用程序 任何注册的银行应用程序 应该能够侦听该 url 并被调用 我已经形成了这样的网址 upi pay pa icic
  • 如何更改 Android 12 启动屏幕中的图标形状?

    我想要矩形形状的启动屏幕图标 而不是 android 12 中的圆形形状 我不相信你可以 如果你看这里的第 3 点 https developer android com about versions 12 features splash
  • 使用后退按钮启动 Activity

    我正在 Android 中开发一个应用程序 我正在寻找解决方案 有一个活动 例如 A1 通过单击按钮 用户可以转到另一个活动 例如 A2 现在 一旦用户完成 A2 活动 他就会单击后退按钮 返回到上一个活动 A1 这是众所周知的事实 A1此
  • 无法登录 Google Play 游戏服务

    我在开发者控制台上使用包名称和正确的签名证书设置了我的游戏 并为其创建了排行榜 但没有创建任何成就 然后 我从以下位置下载了示例 Type A Number Challenge 和 BaseGameUtils https developer
  • 如何通过 AppCompatActivity 使用 YouTube Android 播放器 API

    为了在我的应用程序中播放视频 我决定扩展 YouTube Android Player API 但问题是我的菜单消失了 因为我没有从 AppCompatActivity 扩展 问题是 如何使用 YouTube Android Player
  • 从 sqlite 和 mysql 加载数据微调器

    我试试这个tutorial http nielpoenya blogspot com 2012 08 tutorial android spinner dari database html加载Spinner from sqlite and
  • 制作弹跳动画

    我想做图层的弹跳动画 我已经完成了该图层从右到中心的操作 现在我想将其向后移动一点 然后回到中心 这会产生反弹效果 我想我可以用这样的翻译来做到这一点

随机推荐