使用GPS类获取位置的调试器错误

时间:2017-09-27 10:13:09

标签: android gps location locationmanager locationlistener

创建一个使用GPS检索位置的类时遇到问题。我有主要课程和GPStracker课程。我已经尝试了几个示例和代码,我发现它非常简单,调试器抛出了这个错误,它引导我解决问题,我可能会遇到问题吗?

这是对GPStracker类的类调用

package com.gpasport.controlaccesos.controlaccesos;

import android.content.Context;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
public class TornosList extends AppCompatActivity   {

    //vista gps
    Button btn;

    //vista gps

    ListView listView;
    //añadido
    private static final String Tor = TornosList.class.getSimpleName();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tornoslist);
        listView = (ListView) findViewById(R.id.mobile_list);



        Log.i(Tor,"Estoy en Tornos list");
        Bundle extras = getIntent().getExtras();
        String url_str = extras.getString("URL");
        //adaptamos la url para que quede https://gpasport.miclubonline.net/puertas_club
        url_str =  url_str.substring(0,34);
        url_str =  url_str + "puertas_club";

        //GPS LOCALIZACION
        /*LocationManager locationManager=    (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        GpsLocation locationListener = new GpsLocation();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) locationListener);*/
        //FINAL GPS

        DownloaddWebPageTask task = new DownloadWebPageTask(TornosList.this ,listView);
        task.execute(new String[]{url_str});
        btn = (Button)findViewById(R.id.buttonGps);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(Tor,"Entra en click");
                GPStracker g = new GPStracker(getApplicationContext());
                Log.d(Tor,"Entra en crear gps");
                Location l = g.getLocation();
                Log.d(Tor,"Entra en en location");
                if(l!=null){
                    double lat = l.getLatitude();
                    double lon = l.getLongitude();
                    //Toast toast = Toast.makeText(this, "Codigo verificacion correcto", Toast.LENGTH_LONG);
                    Toast.makeText(getApplicationContext(),"LAT: "+lat+" \n LON: ",Toast.LENGTH_LONG).show();
                }
            }
        });


    }


    //Para poder recopilar los datos de las puertas tenemos que utilizar un AsyncTask
    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {

        Tornos[] aTornos;
        ListView lv1;
        private Context c;

        public DownloadWebPageTask(Context c, ListView lvl){
            this.c = c;
            this.lv1 = lvl;
        }

        protected String doInBackground(String... urls) {
            try {
                //Iniciamos el cliente
                OkHttpClient client = new OkHttpClient();
                //Creamos la request y la respuesta
                Request request =
                        new Request.Builder()
                                .url(urls[0])
                                .build();
                Response response;
                //Log.i(Tor,"Estoy en response");
                //Ejecutamos la request y la guardamos en el objeto response
                response = client.newCall(request).execute();

                if (response.isSuccessful()) {
                    return response.body().string();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "Download failed";
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                Log.d(Tor,"Entra en post");
                Log.d(Tor,result);
                //Instanciamos el JSONhelper
                JsonHelper jh = new JsonHelper();
                //Creamos un JSONObject con la raspuesta que hemos recivido de la response
                JSONObject jsonObject = new JSONObject(result);

                //Iniciamos 2 iterators (En principio con uno ya funcionaria)
                Iterator keys = jsonObject.keys();
                Iterator _key = jsonObject.keys();

                //Cuantos elementos hay en el JSONObject para saber la dimension del array de Tornos
                int i = 0;
                while (_key.hasNext()){
                    _key.next();
                    i++;
                }

                aTornos = new Tornos[i];
                int y = 0;
                while (keys.hasNext()) {
                    //Iniciamos un JSONObject por cada key dentro del JSON
                    JSONObject puertas = jsonObject.getJSONObject(keys.next().toString());
                    //Creamos un iterator para este segundo Object
                    Iterator x = puertas.keys();
                    //Iniciamos el JSONArray que usaremos para pasar de Object a Array
                    JSONArray jsonArray = new JSONArray();

                    //Accedemos a los datos del objeto para guradarlo en el array
                    while (x.hasNext()){
                        String key = (String) x.next();
                        jsonArray.put(puertas.get(key));
                    }

                    //Usando el JSONhelper transformamos el JSONArray a List
                    List list = jh.toList(jsonArray);
                    //Creamos una clase por cada torno que tengamos y lo guardamos en un array de tornos
                    Tornos t = new Tornos(list.get(0).toString(),list.get(1).toString(),keys.toString(), list.get(2).toString(),list.get(3).toString());
                    aTornos[y] = t;
                    y++;
                }

                //Iniciamos el adapter para el ListView
                TornosAdapter adapter = new TornosAdapter (c, R.layout.activity_listview, aTornos);

                lv1.setAdapter(adapter);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }


}

此代码是您单击按钮时创建新对象的GPStracker类。 Log.d()没有写入控制台

GPStracker类:​​

package com.gpasport.controlaccesos.controlaccesos;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

/**
 * Created by asanchez on 27/09/2017.
 */

public class GPStracker implements LocationListener{
    Context context;

    public GPStracker(Context c){
        context = c;
    }

    public Location getLocation(){
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if(isGpsEnabled){
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,6000,10,this);
            Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            return l;
        }else{
            Toast.makeText(context, "Please Enable GPS", Toast.LENGTH_SHORT).show();
        }
        return null;
    }
    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}

我的宣言和许可

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gpasport.controlaccesos.controlaccesos">

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. -->
    <uses-feature android:name="android.hardware.location.gps" />


    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".TornosList"
            android:screenOrientation="portrait"></activity>
        <activity android:name=".visor"></activity>
        <activity
            android:name=".GpsLocation"
            android:screenOrientation="portrait"></activity>
    </application>

</manifest>

该视图包含以下代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.gpasport.controlaccesos.controlaccesos.TornosList">

    <ListView
        android:id="@+id/mobile_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="@drawable/myrect"
        android:dividerHeight="3dp"
        tools:layout_editor_absoluteY="267dp"
        tools:layout_editor_absoluteX="-16dp" />

    <TextView
        android:id="@+id/textViewGps"
        android:layout_width="775dp"
        android:layout_height="99dp"
        android:text="TextView"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="7dp" />

    <Button
        android:id="@+id/buttonGps"
        android:layout_width="508dp"
        android:layout_height="68dp"
        android:text="Button"
        tools:layout_editor_absoluteX="146dp"
        tools:layout_editor_absoluteY="125dp" />


</android.support.constraint.ConstraintLayout>

错误debbuger:

09-27 12:11:31.782 21011-21011/com.gpasport.controlaccesos.controlaccesos E/ViewRootImpl: lhf  @@ scheduleConsumeBatchedInput: mConsumeBatchedInputScheduled = true,mPendingInputEventHead = null,mTraversalScheduled=true, this = ViewRoot{1736210b com.gpasport.controlaccesos.controlaccesos/com.gpasport.controlaccesos.controlaccesos.TornosList,ident = 2}

0 个答案:

没有答案