尝试将数据从子活动返回到MainActivity

时间:2016-03-13 07:44:12

标签: android android-intent nullpointerexception

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

MainActivity

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

}

ActivityMap

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:致命异常:主要                                                                                 java.lang.RuntimeException:传递结果失败   ResultInfo {who = 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)                                                                                 at 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)                                                                                 at dalvik.system.NativeStart.main(Native Method)                                                                              引起: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)                                                                                 at 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(本地方法)

1 个答案:

答案 0 :(得分:2)

你必须初始化LatBox

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