如何在Android中使用位置,适配器和ListView修复此错误?

时间:2014-10-28 10:07:17

标签: android listview android-listview location adapter

大家好我有一个棘手的错误,我无法解决。我正在制作列表视图,当位置服务处于活动状态时我希望如果打开位置我会看时间去一个地方,当位置服务关闭时,我会显示一条消息而不是时间。没什么特别的。但我有一个棘手的错误,如果我有GPS,如此精细的位置,工作,如果我关闭所有位置,工作,但如果我有粗略的位置活动,应用程序崩溃...这是非常棘手的。在我的代码和我的logcat下面。谢谢你们。

全班代码:

package com.example.findmyclients;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;


import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListviewActivity extends Activity{

private ListView lista;
private ListView listaNOGPS;
private List<InterestPoint> listaInteressPoint;
private List<InterestPoint> listaInteressPointNOGPS;
private InterestPoint ip;
private CustomListAdapter adapter;
private CustomListAdapter adapterNOGPS;

public String [][]ArrayTime = new String[1000][6];  //La matrice che conterrà tutti i dati relativi alla lista

public String [][]Dati_history = new String[100][10];
public String [][]Dati_restaurant = new String[100][10];
public String [][]Dati_hotel = new String[100][10];
public String [][]Dati_souvenir = new String[100][10];
public String pathdirectory = "/sdcard/PredappioLiving/";

String[]file_names={"markers_history.xml", "markers_hotel.xml", "markers_restaurant.xml", "markers_souvenir.xml"};
String[]Array_Cat={"Monumenti","Alloggi","Ristoranti","Negozi"};

int nome_luogo = 0;
int categoria = 1;
int auto = 2;
int piedi = 3;
int latitude = 4;
int longitude = 5;

int gps_on= 0;



    @Override
    protected void onCreate (Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        final Activity thiz = this;

        //Get ListView Object from xml
        lista = (ListView) thiz.findViewById(R.id.lista);
        listaNOGPS = (ListView) thiz.findViewById(R.id.lista);

        GPSTracker gpstrack = new GPSTracker(this);
        if (gpstrack.canGetLocation() ) {
            gps_on = 1;
        }

        /* - - - Costruzione della matrice dall'xml - - - */
        /* - - - - - - - - - - - - - - - - - - - - - - - -*/
        int file_choice=-1;
        int n = 0;  //mi serve per riempire bene tutta la matrice
        for (int i = 0; i<file_names.length; i++)
        {
            String file_path = pathdirectory+file_names[i];
            int indice_riempimento = n;

            int returnhistory = file_names[i].compareTo("markers_history.xml");
            int returnhotel = file_names[i].compareTo("markers_hotel.xml");
            int returnrestaurant = file_names[i].compareTo("markers_restaurant.xml");
            int returnsouvenir = file_names[i].compareTo("markers_souvenir.xml");

            if (returnhistory == 0){
                file_choice = 0;
            }
            if (returnhotel == 0){
                file_choice = 1;
            }
            if (returnrestaurant == 0){
                file_choice = 2;
            }
            if (returnsouvenir == 0){
                file_choice = 3;
            }

            // Inizio lettura da XML e popolazione della matrice

            try
            {
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(new FileInputStream(file_path));
                doc.getDocumentElement().normalize();

                NodeList nodi = doc.getElementsByTagName("marker");



                for (int c = 0; c<nodi.getLength(); c++)
                {
                    Element item = (Element) nodi.item(c);
                    String nome = item.getAttribute("name");
                    String destLat = item.getAttribute("lat");
                    String destLong = item.getAttribute("long");

                    Double lat = Double.valueOf(destLat);
                    Double lon = Double.valueOf(destLong);

                    GPSTracker gpsTracker = new GPSTracker(this);

                    String stringMyLatitude = String.valueOf(gpsTracker.latitude);
                    String stringMyLongitude = String.valueOf(gpsTracker.longitude);

                    double currentLat = Double.parseDouble(stringMyLatitude);
                    double currentLong = Double.parseDouble(stringMyLongitude);

                    final float[]distanzadouble = new float[3];
                    Location.distanceBetween(currentLat, currentLong, lat, lon, distanzadouble);

                    float metri = distanzadouble[0];
                    float km = Math.round((double)metri/1000);

                    int minuti_persona = (int)Math.round(metri/125);    //125 metri al minuto -> velocità media di 2,5 m/s
                    int minuti_auto = (int)Math.round(km/0.7);          //700 metri al minuto -> velocità media di 42 km/h 

                    String string_min_a_piedi;
                    String string_min_in_auto;

                    if(minuti_persona <=0)          // Stampa tempo per coprire la distanza
                    {
                        string_min_a_piedi="meno di un minuto";
                    }else
                    {
                        string_min_a_piedi=String.valueOf(minuti_persona);
                    }

                    if(minuti_auto <= 0)
                    {
                        string_min_in_auto="meno di un minuto";                                 
                    }else
                    {
                        string_min_in_auto= String.valueOf(minuti_auto);
                    }

                    ArrayTime[c+n][nome_luogo] = nome;
                    ArrayTime[c+n][categoria] = Array_Cat[file_choice];
                    ArrayTime[c+n][auto] = string_min_in_auto;
                    ArrayTime[c+n][piedi] = string_min_a_piedi;


                }

                n = n+nodi.getLength();


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


        }

        //Arrays.sort(ArrayTime, new ColumnComparator(0));




        //Stampa dell'array sulla lista - - -

        /*
        for(int i = 0; i<6; i++)
        {   
            ip = new InterestPoint();
            ip.nome = "pippo"+i;
            ip.categoria ="cat pippo"+i;
            ip.apiedi = "25";
            ip.inauto = "10";
            listaInteressPoint.add(ip);
        }
        */



        final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );


        if (gps_on == 1) {

            listaInteressPoint = new ArrayList<InterestPoint>();

            for(int i = 0; i<n;i++)
            {
                ip = new InterestPoint();
                ip.nome = ArrayTime[i][nome_luogo];
                ip.categoria = "Categoria: "+ArrayTime[i][categoria];
                ip.inauto = "In auto: " +ArrayTime[i][auto]+ " minuti";
                ip.apiedi = "A piedi: " +ArrayTime[i][piedi]+ " minuti";
                listaInteressPoint.add(ip);
            }

            //Ordinamento
            Collections.sort(listaInteressPoint, new Comparator<InterestPoint>(){

                @Override
                public int compare(InterestPoint elem1, InterestPoint elem2) {

                    return elem1.inauto.compareTo(elem2.inauto);
                }

            });


        }else
        {

            listaInteressPointNOGPS = new ArrayList<InterestPoint>();

            for(int i = 0; i<n;i++)
            {
                ip = new InterestPoint();
                ip.nome = ArrayTime[i][nome_luogo];
                ip.categoria = "Categoria: "+ArrayTime[i][categoria];
                ip.inauto = "In auto:   Attiva la posizione per la distanza";
                ip.apiedi = "A piedi:   in auto e a piedi";
                listaInteressPointNOGPS.add(ip);
            }

            //Ordinamento
            Collections.sort(listaInteressPointNOGPS, new Comparator<InterestPoint>(){

                @Override
                public int compare(InterestPoint elem1, InterestPoint elem2) {

                    return elem1.nome.compareTo(elem2.nome);
                }

            });
        }

       /* 
      //ListView Item Click Listener
            listaNOGPS.setOnItemClickListener(new OnItemClickListener() {


                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {

                //ListView Clicked item index
                        int itemPosition = position;

                        InterestPoint item = adapter.getItem(position);

                        Intent piu_info = new Intent(thiz, MoreInfoActivity.class); 
                        piu_info.putExtra("nome", item.nome);
                        startActivity(piu_info);
                        //ListView clicked item value
                        //int itemValue = (int) lista.getItemAtPosition(position);

                        //Show Alert
                        Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();

                }
            });

            */  

        //ListView Item Click Listener
        lista.setOnItemClickListener(new OnItemClickListener() {


            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                    if (gps_on == 1){
                        //ListView Clicked item index
                        int itemPosition = position;

                        InterestPoint item = adapter.getItem(position);

                        Intent piu_info = new Intent(thiz, MoreInfoActivity.class); 
                        piu_info.putExtra("nome", item.nome);
                        startActivity(piu_info);
                        //ListView clicked item value
                        //int itemValue = (int) lista.getItemAtPosition(position);

                        //Show Alert
                        Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();
                    }else
                    {
                        //ListView Clicked item index
                        int itemPosition = position;

                        InterestPoint item = adapterNOGPS.getItem(position);

                        Intent piu_info = new Intent(thiz, MoreInfoActivity.class); 
                        piu_info.putExtra("nome", item.nome);
                        startActivity(piu_info);
                        //ListView clicked item value
                        //int itemValue = (int) lista.getItemAtPosition(position);

                        //Show Alert
                        Toast.makeText(getApplicationContext(), "Position :"+itemPosition+" ListItem :"+ item.nome, Toast.LENGTH_LONG).show();
                    }


            }
        });

    }

    @Override
        protected void onResume() {
            super.onResume();

            final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
            adapter = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPoint);
            adapterNOGPS = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPointNOGPS);

            if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {

                lista.setAdapter(adapter);
            }else
            {
                listaNOGPS.setAdapter(adapterNOGPS);
            }
        }
}

Logcat:

10-28 10:53:53.106: E/AndroidRuntime(445): FATAL EXCEPTION: main
10-28 10:53:53.106: E/AndroidRuntime(445): Process: com.example.findmyclients, PID: 445
10-28 10:53:53.106: E/AndroidRuntime(445): java.lang.RuntimeException: Unable to resume activity {com.example.findmyclients/com.example.findmyclients.ListviewActivity}: java.lang.NullPointerException
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3076)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3105)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.access$900(ActivityThread.java:175)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.os.Looper.loop(Looper.java:146)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.main(ActivityThread.java:5602)
10-28 10:53:53.106: E/AndroidRuntime(445):  at java.lang.reflect.Method.invokeNative(Native Method)
10-28 10:53:53.106: E/AndroidRuntime(445):  at java.lang.reflect.Method.invoke(Method.java:515)
10-28 10:53:53.106: E/AndroidRuntime(445):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
10-28 10:53:53.106: E/AndroidRuntime(445):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
10-28 10:53:53.106: E/AndroidRuntime(445):  at dalvik.system.NativeStart.main(Native Method)
10-28 10:53:53.106: E/AndroidRuntime(445): Caused by: java.lang.NullPointerException
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.widget.ListView.setAdapter(ListView.java:486)
10-28 10:53:53.106: E/AndroidRuntime(445):  at com.example.findmyclients.ListviewActivity.onResume(ListviewActivity.java:356)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1198)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.Activity.performResume(Activity.java:5530)
10-28 10:53:53.106: E/AndroidRuntime(445):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3066)
10-28 10:53:53.106: E/AndroidRuntime(445):  ... 12 more
10-28 10:53:53.161: I/Process(445): Sending signal. PID: 445 SIG: 9

P.S。:粗略位置变量“gps_on”正确设置为“1”

1 个答案:

答案 0 :(得分:1)

1。

if (gps_on == 1) {

            listaInteressPoint = new ArrayList<InterestPoint>();  
//rest of the code
} else {  
            listaInteressPointNOGPS = new ArrayList<InterestPoint>();
//rest of the code
}

2。 PS:使用粗略位置变量“gps_on”正确设置为“1” < / p>

所以

来自onResume()

3。

   adapter = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPoint);
            adapterNOGPS = new CustomListAdapter(getApplicationContext(), R.layout.list_item, listaInteressPointNOGPS);

            if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {

                lista.setAdapter(adapter);
            }else
            {
                listaNOGPS.setAdapter(adapterNOGPS);
            }  

您获得的错误是getCount()的{​​{1}},它已初始化但为空,未填充。在这种情况下,list因此gps_on==1不会被访问。

您可以更改listaInteressPointNOGPS中的if,并在特定粗略位置激活的情况下检查或条件可能......

来自logcat的重要行

onResume()

从ListviewActivity.java

检查哪一行是356行