簡體   English   中英

通過其他方法訪問變量

[英]Access variables from another method

我正在嘗試使用當前位置在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
            }

    }
});

    }


}

您可能應該研究范圍成員變量 問題是,您不能在一個方法中聲明一件事,然后嘗試從另一方法訪問它。

因此,我們將該事物聲明為成員變量,並在一個方法中對其進行定義,然后可以在另一方法中使用它。

像這樣(我用**標記了我的評論):

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
            }

        }
    });

    }


}

您在變量范圍方面遇到問題。 您要初始化的myLatDouble和myLon Double僅存在於創建它們的onLocationChanged方法中。 您將必須在其他位置聲明它們,以使它們在嘗試訪問它們時不會超出范圍,或者必須將它們作為參數傳遞到nameValuePairs代碼中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM