【问题标题】:Access variables from another method从其他方法访问变量
【发布时间】:2012-08-20 21:05:01
【问题描述】:

我正在尝试使用当前位置在 android 中提交用户注册表单。我是 android 和 java 开发的新手。当我尝试在我的名称值对代码中访问 onLocationChanged 方法的 myLat 和 myLan 时,它无法找到这两个变量。如何访问我的名称值对代码中的两个变量。

package com.imran;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.google.android.gcm.GCMRegistrar;
import com.google.android.maps.MyLocationOverlay;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;

public class Register extends Activity {




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        final EditText email_id = (EditText)  findViewById(R.id.email_id) ;
        final EditText name = (EditText) findViewById(R.id.name);
        final EditText password = (EditText) findViewById(R.id.password);
        Button button = (Button) findViewById(R.id.button1) ;



        //generate GCM id
        GCMRegistrar.checkDevice(this);
        GCMRegistrar.checkManifest(this);
        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) {
          GCMRegistrar.register(this, "12356");

        } else {
        String TAG = null;
        Log.v(TAG, regId);

        }
        //generate GCM id ended
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy); 
        //get current location

        LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        LocationListener listner = new LocationListener() {

            @Override
            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderDisabled(String arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLocationChanged(Location location) {
                double myLonDouble = location.getLongitude();
            final String myLon = Double.toString(myLonDouble);
                double myLatDouble = location.getLatitude();
                final String myLat = Double.toString(myLatDouble);

            }
        };
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listner);



        //end get current location

        button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        //postData();
          HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://xyz.com/folder/register.php");

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("email", email_id.getText().toString()));
                nameValuePairs.add(new BasicNameValuePair("name", name.getText().toString()));
                nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
                nameValuePairs.add(new BasicNameValuePair("regid", regId));
                nameValuePairs.add(new BasicNameValuePair("uid", "2"));
                nameValuePairs.add(new BasicNameValuePair("lat",myLat ));
                nameValuePairs.add(new BasicNameValuePair("lon",myLon));
               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
               //Toast.makeText(this, resId, duration)
                HttpResponse response = httpclient.execute(httppost);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }

    }
});

    }


}

【问题讨论】:

    标签: java android oop geolocation


    【解决方案1】:

    您可能应该学习scopemember variables。问题是,你不能在一个方法中声明一件事,然后尝试从另一个方法访问它。

    所以,我们将这个东西声明为成员变量,并在一个方法中定义它,然后它可以在另一个方法中使用。

    像这样(我用**标记了我的cmets):

    public class Register extends Activity {
    
        // "private" means it can only be accessed from this class
        private String myLat = null; // ** Declare myLat
        private String myLon = null; // ** Declare myLon
    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_register);
            final EditText email_id = (EditText)  findViewById(R.id.email_id) ;
            final EditText name = (EditText) findViewById(R.id.name);
            final EditText password = (EditText) findViewById(R.id.password);
            Button button = (Button) findViewById(R.id.button1) ;
    
    
    
            //generate GCM id
            GCMRegistrar.checkDevice(this);
            GCMRegistrar.checkManifest(this);
            final String regId = GCMRegistrar.getRegistrationId(this);
            if (regId.equals("")) {
              GCMRegistrar.register(this, "12356");
    
            } else {
            String TAG = null;
            Log.v(TAG, regId);
    
            }
            //generate GCM id ended
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy); 
            //get current location
    
            LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            LocationListener listner = new LocationListener() {
    
                @Override
                public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                    // TODO Auto-generated method stub
    
                }
    
                @Override
                public void onProviderEnabled(String arg0) {
                    // TODO Auto-generated method stub
    
                }
    
                @Override
                public void onProviderDisabled(String arg0) {
                    // TODO Auto-generated method stub
    
                }
    
                @Override
                public void onLocationChanged(Location location) {
                    double myLonDouble = location.getLongitude();
                    myLon = Double.toString(myLonDouble); // ** Define myLon
                    double myLatDouble = location.getLatitude();
                    myLat = Double.toString(myLatDouble); // ** Define myLat
    
                }
            };
            manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listner);
    
    
    
            //end get current location
    
            button.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View arg0) {
            // TODO Auto-generated method stub
            // ** Check if they have been defined
            if (myLat == null || myLon == null)
                return;
    
            //postData();
              HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://xyz.com/folder/register.php");
    
                try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("email", email_id.getText().toString()));
                nameValuePairs.add(new BasicNameValuePair("name", name.getText().toString()));
                nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
                nameValuePairs.add(new BasicNameValuePair("regid", regId));
                nameValuePairs.add(new BasicNameValuePair("uid", "2"));
                nameValuePairs.add(new BasicNameValuePair("lat",myLat ));
                nameValuePairs.add(new BasicNameValuePair("lon",myLon));
                   httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
                // Execute HTTP Post Request
                   //Toast.makeText(this, resId, duration)
                HttpResponse response = httpclient.execute(httppost);
    
                } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                } catch (IOException e) {
                // TODO Auto-generated catch block
                }
    
            }
        });
    
        }
    
    
    }
    

    【讨论】:

    • 感谢 Eric 的支持和资源。
    【解决方案2】:

    您的变量范围有问题。您正在初始化的 myLatDouble 和 myLon Double 仅存在于创建它们的 onLocationChanged 方法中。您必须在不同的地方声明它们,这样当您尝试访问它们时它们不会超出范围,或者您必须将它们作为参数传递到 nameValuePairs 代码中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2015-07-30
      • 2016-10-25
      • 2017-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多