gpt4 book ai didi

android - 尝试将数据从子 Activity 返回到 MainActivity 时出现 NullPointerException

转载 作者:行者123 更新时间:2023-11-29 20:03:17 25 4
gpt4 key购买 nike

我正在尝试实现一个启动子 Activity 的 Android 应用程序,它将计算我当前位置的坐标。但是,在尝试将数据发送回 MainActivity 时,我的 onActivityResult 方法中出现了 NullPointerException。这是两个类:

主要 Activity

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;



public class MainActivity extends AppCompatActivity{

//Globals
public String uname = null;
//private MyLocationReceiver myLocationReceiver;
public double lat = 0;
public double lng = 0;
public LatLng curr_pos;
public final String NULL_STRING = "NULL";

//Get GUI handles
public Button sendButton; //
public EditText username;
public Button MapButton; //
public EditText LatBox;
public EditText LngBox;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String LatText = data.getStringExtra("LatValue");
String LngText = data.getStringExtra("LngValue");
LatBox.setText(LatText); // <- GETTING NULLPOINTER HERE
LngBox.setText(LngText); // <- GETTING NULLPOINTER HERE
}
}
}

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
//set GUI for MainActivity
setContentView(R.layout.activity_main);

//EventBus.getDefault().register(this);
//Log.d("Register", "EventBus registered in onCreate");

MapButton = (Button) findViewById(R.id.locationButton);
//Call the class which will handle finding coordinates
MapButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent MapIntent = new Intent(getApplicationContext(), ActivityMap.class);
startActivityForResult(MapIntent, 1);
}
});


sendButton = (Button) findViewById(R.id.Submit);
//Set action for Button
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

//Get username from user
username = (EditText) findViewById(R.id.UsernameText);
uname = username.getText().toString();

//Generate intent to start IntentService
Intent i = new Intent(getApplicationContext(), Register.class);

//Put the extra field of username
i.putExtra("username", uname);
i.putExtra("latitude", lat);
i.putExtra("longitude", lng);
i.putExtra("type", "meetup.be2015.gcm_meetup.MAIN_ACTIVITY");

//Start the IntentService on a different thread
startService(i);
}
});
}

}

Activity map

import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Looper;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import java.util.logging.Handler;

public class ActivityMap extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener{

protected GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
protected Location mLastLocation;
public LocationListener listener;
protected final String TAG = getClass().getSimpleName();
public EditText t1;
public EditText t2;
public Button b1;
public final String NULL = "NULL";


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

t1 = (EditText)findViewById(R.id.editText1);
t2 = (EditText)findViewById(R.id.editText2);
b1 = (Button)findViewById(R.id.BackButton);

buildGoogleApiClient();
mGoogleApiClient.connect();

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
if (mLastLocation != null) {
i.putExtra("LatValue",String.valueOf(mLastLocation.getLatitude()));
i.putExtra("LngValue",String.valueOf(mLastLocation.getLongitude()));
setResult(RESULT_OK, i);
finish();
} else {
i.putExtra("LatValue","NULL");
i.putExtra("LngValue","NULL");
setResult(RESULT_OK, i);
finish();
}
}
});
}

@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}


@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}

protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
Log.d(TAG,"Built Client successfully...");
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG,"ConnectionFailed() with code "+connectionResult.getErrorCode());
}

@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "In onConnected..");

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

if(mLastLocation == null) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

else{
t1.setText(String.valueOf(mLastLocation.getLatitude()));
t2.setText(String.valueOf(mLastLocation.getLongitude()));
//LatLng lng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());

Toast.makeText(this, "Retrieved location from FusedLocation", Toast.LENGTH_LONG).show();

Intent intent = new Intent();
intent.putExtra("LatValue",String.valueOf(mLastLocation.getLatitude()));
intent.putExtra("LngValue", String.valueOf(mLastLocation.getLongitude()));
setResult(RESULT_OK, intent);
finish();
}
}

@Override
public void onConnectionSuspended(int i) {
Log.d(TAG,"ConnectionSuspended() with code "+i);
}

@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
if(latitude != 0 && longitude != 0) {
t1.setText(String.valueOf(latitude));
t2.setText(String.valueOf(longitude));

Toast.makeText(this, "Retrieved Location from onLocationChanged...", Toast.LENGTH_LONG).show();

Intent intent = new Intent();
intent.putExtra("LatValue",String.valueOf(mLastLocation.getLatitude()));
intent.putExtra("LngValue", String.valueOf(mLastLocation.getLongitude()));
setResult(RESULT_OK, intent);
finish();
}
else {
t1.setText(NULL);
t2.setText(NULL);

Toast.makeText(this, "Problem with location...", Toast.LENGTH_LONG).show();

Intent intent = new Intent();
intent.putExtra("LatValue", "NULL");
intent.putExtra("LngValue", "NULL");
setResult(RESULT_OK, intent);
finish();
}
}

编辑:这是我的 LogCat

03-13 13:06:59.940 14638-14638/meetup.be2015.gcm_meetup E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { (has extras) }} to activity {meetup.be2015.gcm_meetup/meetup.be2015.gcm_meetup.MainActivity}: java.lang.NullPointerException at android.app.ActivityThread.deliverResults(ActivityThread.java:3216) at android.app.ActivityThread.handleSendResult(ActivityThread.java:3259) at android.app.ActivityThread.access$1200(ActivityThread.java:140) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:174) at android.app.ActivityThread.main(ActivityThread.java:4952) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at meetup.be2015.gcm_meetup.MainActivity.onActivityResult(MainActivity.java:60) at android.app.Activity.dispatchActivityResult(Activity.java:5372) at android.app.ActivityThread.deliverResults(ActivityThread.java:3212) at android.app.ActivityThread.handleSendResult(ActivityThread.java:3259)  at android.app.ActivityThread.access$1200(ActivityThread.java:140)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285)  at android.os.Handler.dispatchMessage(Handler.java:99)  at android.os.Looper.loop(Looper.java:174)  at android.app.ActivityThread.main(ActivityThread.java:4952)  at java.lang.reflect.Method.invokeNative(Native Method)  at java.lang.reflect.Method.invoke(Method.java:511)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)  at dalvik.system.NativeStart.main(Native Method)

最佳答案

你必须初始化LatBox

LatBox = (EditText) findViewById(R.id.xxx);

关于android - 尝试将数据从子 Activity 返回到 MainActivity 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35967832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com