java.lang.NullPointerException : uri - Turning on Location through Alert Dialog

标签 java android

您好,我正在开发一个程序,它可以获取用户的当前位置并将其发送给用户的首选联系人之一。现在,某些用户可能已关闭其位置,因此我添加了一个对话框警报,要求他们按"is"来启用其位置。单击"is"时,程序崩溃并出现错误:

 Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.michael79.handydoc/com.example.michael79.handydoc.emergencyActivity}: java.lang.NullPointerException: uri

这是我的代码:

public class emergencyActivity extends AppCompatActivity implements LocationListener {

private static final int REQUEST_CODE =1;

TextView t1;
LocationManager locationManager;
String mprovider;
//Context context=this;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_emergency);

    t1=(TextView) findViewById(R.id.textContact);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    mprovider = locationManager.getBestProvider(criteria, false);
    displayLocationSettingsRequest(this);
    if (mprovider != null && !mprovider.equals("")) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Location location = locationManager.getLastKnownLocation(mprovider);
        locationManager.requestLocationUpdates(mprovider, 15000, 1, this);

        if (location != null)
            onLocationChanged(location);
        else
            Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
    }

}
    public void getContact(View v){
        Uri uri = Uri.parse("content://contacts");
        Intent intent = new Intent(Intent.ACTION_PICK, uri);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
        startActivityForResult(intent, REQUEST_CODE);
    }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if(resultCode != Activity.RESULT_CANCELED) {
            Uri uri = intent.getData();
        String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
        Cursor cursor = getContentResolver().query(uri, projection,
                null, null, null);
        cursor.moveToFirst();
        int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
        String number = cursor.getString(numberColumnIndex);
        int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
        String name = cursor.getString(nameColumnIndex);
        Toast.makeText(getApplicationContext(), "Number" + number + " Name" + name, Toast.LENGTH_LONG).show();
        t1.setText(number);
        //Log.d(TAG, "ZZZ number : " + number +" , name : "+name);
    }


};

public  void sendAlert(View v){
    String phoneNo = t1.getText().toString();
    String sms = "I need your help please i'm in distress";

    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, sms, null, null);
        Toast.makeText(getApplicationContext(), "SMS Sent!",
                Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(),
                "SMS faild, please try again later!",
                Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

@Override
public void onLocationChanged(Location location) {
    TextView cord = (TextView) findViewById(R.id.textView26);
    cord.setText("Current Longitude:" + location.getLongitude()+"  Current Latitude:"+location.getLatitude());

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}
private void displayLocationSettingsRequest(Context context) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i("show", "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i("show", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(emergencyActivity.this, REQUEST_CODE);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i("show", "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i("show", "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}

我检查了如何解决该问题,但我得到的解决方案无法解决它们。

最佳答案

private static final int REQUEST_CODE =5;
private static final int STATUS_REQUEST_CODE =2;


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if(requestCode!=RESULT_CANCELED) {
            if(requestCode==REQUEST_CODE) {

            Uri uri = intent.getData();
            String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME};
            Cursor cursor = getContentResolver().query(uri, projection,
                    null, null, null);
            cursor.moveToFirst();
            int numberColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
            String number = cursor.getString(numberColumnIndex);
            int nameColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
            String name = cursor.getString(nameColumnIndex);
            Toast.makeText(getApplicationContext(), "Number" + number + " Name" + name, Toast.LENGTH_LONG).show();
            t1.setText(number);
            //Log.d(TAG, "ZZZ number : " + number +" , name : "+name);
        }
    }


};



    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    Log.i("show", "All location settings are satisfied.");
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    Log.i("show", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(emergencyActivity.this, STATUS_REQUEST_CODE);
                    } catch (IntentSender.SendIntentException e) {
                        Log.i("show", "PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    Log.i("show", "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}

经过一段时间的阅读、测试和修复后,我为 status.startResolutionForResult() 创建了一个请求代码,并更改了 onActivityResult() 中的条件语句,修复了我的问题

关于java.lang.NullPointerException : uri - Turning on Location through Alert Dialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43131192/

相关文章:

android - ViewPager 中的不同配置

java - 多个 JButton 的 MVC 模式

java - 由不同类的线程更新的值不会反射(reflect)在 java 中的另一个类中

android - Android 中线性布局的相对堆叠?

Android RecyclerView重力问题

java - 使用 HttpUrlConnection 在没有任何参数的情况下在服务器上执行 php 脚本

android - RecyclerView - 如何平滑滚动到某个位置的项目顶部?

java - 在考虑夏令时的同时通过Jackson序列化java.sql.Date

java - Java如何计算原始数组的长度?

java - Lambda 表达式与方法引用实现细节