草庐IT

android - Volley Get 请求根本没有执行

coder 2023-12-14 原文

public class RouteFragment extends Fragment implements LocationListener {

MapView mMapView;
private GoogleMap googleMap;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private String startLocation, endLocation = "";
private LatLng start, end;
private CarouselView carouselView;
private String estimatedDistance = "0km";
private TextView costPerMile;
public int counter = 0;
public static final String[] vehicleList = {"ambulance", "wheelchair", "star"};
private int chosenVehicle = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_route, container, false);
    final Context context = getActivity().getApplicationContext();
    Bundle bundle = this.getArguments();
    if (bundle != null) {
        startLocation = bundle.getString("start_location");
        endLocation = bundle.getString("end_location");
    }

    RequestQueue queue2 = Volley.newRequestQueue(context);
    StringRequest getRequest2 = new StringRequest(Request.Method.GET, (MainActivity.url + "/api/getLocation" + "?place=" + startLocation),
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jresponse = new JSONObject(response);
                        Log.d("END", response);
                        Double lat = Double.valueOf(jresponse.getJSONObject("data").getString("lat"));
                        Double lng = Double.valueOf(jresponse.getJSONObject("data").getString("lng"));
                        start = new LatLng(lat,lng);

                    } catch (JSONException e) {
                        Log.d("ASD", "ERROR");
                        Log.d("ERROR", String.valueOf(e));
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    Log.d("Error.Response", String.valueOf(error));
                }
            }
    ) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError
        {
            Map<String, String> headers = new HashMap<String, String>();
            //Log.d("ASD", MainActivity.token);
            headers.put("x-access-token", MainActivity.token);
            headers.put("Content-Type","application/x-www-form-urlencoded");
            return headers;
        }
    };

    queue2.add(getRequest2);

    checkLocationPermission();
    FloatingActionButton fab = getActivity().findViewById(R.id.fab);
    fab.setVisibility(View.INVISIBLE);
    mMapView = view.findViewById(R.id.mapRoute);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume(); // needed to get the map to display immediately
    Log.d("ASD", "ASDASDASDASDASD");

当我运行此代码时,会打印检查 1 和检查 2(日志),但 Volley 请求既没有给出错误也没有给出响应(因此没有其他日志消息被打印)。我尝试将 url 更改为无效的内容,然后它引发了 404 错误,但我确定 url 是正确的。我已经看了好几个小时了,当我在另一个 fragment 中运行它时,它运行得很完美。但它不会在这里运行,或者当我将它放在另一个按钮的 onClickListener 中时。

最佳答案

所以发现自己的错误:

创建谷歌地图是一个异步函数,就像我后端(node js)中的代码一样。为了解决这个问题,我将所有代码都放在了 onMapCreate 函数中。

//This goes in the onCreate
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
            .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

//This overrides the onMapReady function
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
    StringRequest getRequest = new StringRequest(Request.Method.GET, (MainActivity.url + "/api/getLocation" + "?place=" + startLocation),
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jresponse = new JSONObject(response);
                    }
                    catch (JSONException e) {
                                    Log.d("ASD", "ERROR");
                                    Log.d("ERROR", String.valueOf(e));
                                    e.printStackTrace();
                    }
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    Log.d("Error.Response", String.valueOf(error));
                    }
            }
    )
queue.add(getRequest);

关于android - Volley Get 请求根本没有执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51902828/

有关android - Volley Get 请求根本没有执行的更多相关文章

  1. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  2. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  3. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  4. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  5. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  6. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  7. ruby - 为什么 Ruby 的 each 迭代器先执行? - 2

    我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试

  8. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  9. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

  10. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

随机推荐