尝试将数据从子活动返回到 MainActivity 时获取 NullPointerException

Posted

技术标签:

【中文标题】尝试将数据从子活动返回到 MainActivity 时获取 NullPointerException【英文标题】:Getting a NullPointerException while trying to return data from a sub-activity to MainActivity 【发布时间】:2016-06-28 07:52:31 【问题描述】:

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

主要活动

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);
        
    );



活动地图

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: 致命异常: main java.lang.RuntimeException:传递结果失败 ResultInfowho=null, request=1, result=-1, data=Intent (有附加功能) 到活动 meetup.be2015.gcm_meetup/meetup.be2015.gcm_meetup.MainActivity: java.lang.NullPointerException 在 android.app.ActivityThread.deliverResults(ActivityThread.java:3216) 在 android.app.ActivityThread.handleSendResult(ActivityThread.java:3259) 在 android.app.ActivityThread.access$1200(ActivityThread.java:140) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285) 在 android.os.Handler.dispatchMessage(Handler.java:99) 在 android.os.Looper.loop(Looper.java:174) 在 android.app.ActivityThread.main(ActivityThread.java:4952) 在 java.lang.reflect.Method.invokeNative(Native Method) 在 java.lang.reflect.Method.invoke(Method.java:511) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) 在 dalvik.system.NativeStart.main(本机方法) 引起:java.lang.NullPointerException 在 meetup.be2015.gcm_meetup.MainActivity.onActivityResult(MainActivity.java:60) 在 android.app.Activity.dispatchActivityResult(Activity.java:5372) 在 android.app.ActivityThread.deliverResults(ActivityThread.java:3212) 在 android.app.ActivityThread.handleSendResult(ActivityThread.java:3259) 在 android.app.ActivityThread.access$1200(ActivityThread.java:140) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285) 在 android.os.Handler.dispatchMessage(Handler.java:99) 在 android.os.Looper.loop(Looper.java:174) 在 android.app.ActivityThread.main(ActivityThread.java:4952) 在 java.lang.reflect.Method.invokeNative(Native Method) 在 java.lang.reflect.Method.invoke(Method.java:511) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) 在 dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

使用断点调试您的代码并找出错误所在。第二个活动返回的数据没有错误。 【参考方案1】:

你必须初始化 LatBox

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

【讨论】:

天啊!天哪,我怎么会错过呢?谢谢,伙计! 是的!完毕!谢了哥们!轻信率最高,嗯?

以上是关于尝试将数据从子活动返回到 MainActivity 时获取 NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章

如何将片段活动添加到 MainActivity.java 或 MainActivity.kt

无法从一个活动获取数据到另一个活动

MainActivity中的BroadcastReceiver不接收广播意图

WebViewClient将数据返回到Activity onPageFinished

在不同的活动中将数据从 ListView 传递到 TextView,Android

从活动传递数据到类扩展视图