从另一种方法访问变量 [英] Access variables from another method

查看:165
本文介绍了从另一种方法访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Android中使用当前的位置提交用户登记表。我是新来的Andr​​oid和Java开发。当我尝试访问onLocationChanged方法myLat和Mylan公司以我的名义值对code,它是无法找到这两个变量。如何访问我的名值对code这两个变量。

 包com.imran;

进口java.io.IOException异常;
进口的java.util.ArrayList;
进口的java.util.List;

进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.apache.http.message.BasicNameValuePair;

进口com.google.android.gcm.GCMRegistrar;
进口com.google.android.maps.MyLocationOverlay;

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

公共类注册扩展活动{




    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_register);
        最后的EditText email_id =(EditText上)findViewById(R.id.email_id);
        最后的EditText名=(EditText上)findViewById(R.id.name);
        最后的EditText密码=(EditText上)findViewById(R.id.password);
        Button按钮=(按钮)findViewById(R.id.button1);



        //生成GCM ID
        GCMRegistrar.checkDevice(本);
        GCMRegistrar.checkManifest(本);
        最后弦乐REGID = GCMRegistrar.getRegistrationId(本);
        如果(regId.equals()){
          GCMRegistrar.register(这一点,12356);

        } 其他 {
        字符串变量= NULL;
        Log.v(TAG,REGID);

        }
        //生成GCM ID结束
        。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
        StrictMode.setThreadPolicy(政策);
        //获得当前位置

        LocationManager经理=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        LocationListener的听者=新LocationListener的(){

            @覆盖
            公共无效onStatusChanged(字符串为arg0,INT ARG1,捆绑ARG2){
                // TODO自动生成方法存根

            }

            @覆盖
            公共无效onProviderEnabled(字符串为arg0){
                // TODO自动生成方法存根

            }

            @覆盖
            公共无效onProviderDisabled(字符串为arg0){
                // TODO自动生成方法存根

            }

            @覆盖
            公共无效onLocationChanged(位置定位){
                双myLonDouble = location.getLongitude();
            最后弦乐myLon = Double.toString(myLonDouble);
                双myLatDouble = location.getLatitude();
                最后弦乐myLat = Double.toString(myLatDouble);

            }
        };
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,听者);



        //年底获得当前位置

        button.setOnClickListener(新View.OnClickListener(){

    @覆盖
    公共无效的onClick(查看为arg0){
        // TODO自动生成方法存根
        // POSTDATA();
          HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httppost =新HttpPost(http://xyz.com/folder/register.php);

            尝试 {
                //添加数据
                名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
                nameValuePairs.add(新BasicNameValuePair(电子邮件,email_id.g​​etText()的toString()));
                nameValuePairs.add(新BasicNameValuePair(姓名,name.getText()的toString())。);
                nameValuePairs.add(新BasicNameValuePair(密码,password.getText()的toString()));
                nameValuePairs.add(新BasicNameValuePair(REGID,REGID));
                nameValuePairs.add(新BasicNameValuePair(流体,2));
                nameValuePairs.add(新BasicNameValuePair(土地增值税,myLat));
                nameValuePairs.add(新BasicNameValuePair(LON,myLon));
               httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));

                //执行HTTP POST请求
               //Toast.makeText(this,渣油,持续时间)
                HTT presponse响应= httpclient.execute(httppost);

            }赶上(ClientProtocolException E){
                // TODO自动生成的catch块
            }赶上(IOException异常E){
                // TODO自动生成的catch块
            }

    }
});

    }


}
 

解决方案

您或许应该学习上的范围成员变量的。关键是,你不能宣布一件事情在一个方法,然后尝试从另外一个方法来访问它。

因此​​,我们宣布东西作为成员变量,在一个方法定义它,那么就可以在另一种方法中使用。

像这样(我已经打上我的意见与 ** ):

 公共类注册扩展活动{

    //私有意味着它只能从这个类来访问
    私人字符串myLat = NULL; // **声明myLat
    私人字符串myLon = NULL; // **声明myLon


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_register);
        最后的EditText email_id =(EditText上)findViewById(R.id.email_id);
        最后的EditText名=(EditText上)findViewById(R.id.name);
        最后的EditText密码=(EditText上)findViewById(R.id.password);
        Button按钮=(按钮)findViewById(R.id.button1);



        //生成GCM ID
        GCMRegistrar.checkDevice(本);
        GCMRegistrar.checkManifest(本);
        最后弦乐REGID = GCMRegistrar.getRegistrationId(本);
        如果(regId.equals()){
          GCMRegistrar.register(这一点,12356);

        } 其他 {
        字符串变量= NULL;
        Log.v(TAG,REGID);

        }
        //生成GCM ID结束
        。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
        StrictMode.setThreadPolicy(政策);
        //获得当前位置

        LocationManager经理=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        LocationListener的听者=新LocationListener的(){

            @覆盖
            公共无效onStatusChanged(字符串为arg0,INT ARG1,捆绑ARG2){
                // TODO自动生成方法存根

            }

            @覆盖
            公共无效onProviderEnabled(字符串为arg0){
                // TODO自动生成方法存根

            }

            @覆盖
            公共无效onProviderDisabled(字符串为arg0){
                // TODO自动生成方法存根

            }

            @覆盖
            公共无效onLocationChanged(位置定位){
                双myLonDouble = location.getLongitude();
                myLon = Double.toString(myLonDouble); // **定义myLon
                双myLatDouble = location.getLatitude();
                myLat = Double.toString(myLatDouble); // **定义myLat

            }
        };
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,听者);



        //年底获得当前位置

        button.setOnClickListener(新View.OnClickListener(){

        @覆盖
        公共无效的onClick(查看为arg0){
        // TODO自动生成方法存根
        // **检查是否已定义
        如果(myLat == NULL || myLon == NULL)
            返回;

        // POSTDATA();
          HttpClient的HttpClient的=新DefaultHttpClient();
            HttpPost httppost =新HttpPost(http://xyz.com/folder/register.php);

            尝试 {
            //添加数据
            名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
            nameValuePairs.add(新BasicNameValuePair(电子邮件,email_id.g​​etText()的toString()));
            nameValuePairs.add(新BasicNameValuePair(姓名,name.getText()的toString())。);
            nameValuePairs.add(新BasicNameValuePair(密码,password.getText()的toString()));
            nameValuePairs.add(新BasicNameValuePair(REGID,REGID));
            nameValuePairs.add(新BasicNameValuePair(流体,2));
            nameValuePairs.add(新BasicNameValuePair(土地增值税,myLat));
            nameValuePairs.add(新BasicNameValuePair(LON,myLon));
               httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));

            //执行HTTP POST请求
               //Toast.makeText(this,渣油,持续时间)
            HTT presponse响应= httpclient.execute(httppost);

            }赶上(ClientProtocolException E){
            // TODO自动生成的catch块
            }赶上(IOException异常E){
            // TODO自动生成的catch块
            }

        }
    });

    }


}
 

i am trying to submit user registration form in android with current location. I am new to android and java development. when i try to access myLat and myLan of the onLocationChanged method in my name value pairs code , it is unable to find both the variables. How can i access both the variables in my name value pair code.

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
            }

    }
});

    }


}

解决方案

You should probably study up on scope and member variables. The thing is, you can't declare one thing in one method then attempt to access it from another method.

So, we declare that thing as a member variable, and define it in one method, then it can be used in another method.

Like so (I've marked my comments with **):

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
            }

        }
    });

    }


}

这篇关于从另一种方法访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆